-
Notifications
You must be signed in to change notification settings - Fork 1
/
parinfer.lua
1773 lines (1502 loc) · 49.5 KB
/
parinfer.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- parinfer.lua - a Parinfer implementation in Lua
-- v0.1.0
-- https://github.com/oakmac/parinfer-lua
--
-- More information about Parinfer can be found here:
-- http://shaunlebron.github.io/parinfer/
--
-- Copyright (c) 2021, Chris Oakman
-- Released under the ISC license
-- https://github.com/oakmac/parinfer-lua/blob/master/LICENSE.md
local M = {}
-- forward declarations
local resetParenTrail, rememberParenTrail, updateRememberedParenTrail
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Constants
local UINT_NULL = -999
local INDENT_MODE = "INDENT_MODE"
local PAREN_MODE = "PAREN_MODE"
local BACKSLASH = "\\"
local BLANK_SPACE = " "
local DOUBLE_SPACE = " "
local DOUBLE_QUOTE = '"'
local NEWLINE = "\n"
local TAB = "\t"
-- local LINE_ENDING_REGEX = /\r?\n/
local MATCH_PAREN = {}
MATCH_PAREN["{"] = "}"
MATCH_PAREN["}"] = "{"
MATCH_PAREN["["] = "]"
MATCH_PAREN["]"] = "["
MATCH_PAREN["("] = ")"
MATCH_PAREN[")"] = "("
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Development Helpers
-- NOTE: this is useful for development and debugging purposes
-- not required for the core library
-- local inspect = require("libs/inspect")
-- toggle this to check the asserts during development
local RUN_ASSERTS = false
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Type Predicates
local function isBoolean(x)
return x == true or x == false
end
local function isTable(t)
return type(t) == "table"
end
local function isInteger(i)
return type(i) == "number" and i == math.floor(i)
end
if RUN_ASSERTS then
assert(isInteger(1))
assert(isInteger(-97))
assert(not isInteger(3.14))
assert(not isInteger())
assert(not isInteger({}))
assert(not isInteger("6"))
end
local function isPositiveInt(i)
return isInteger(i) and i >= 0
end
local function isString(s)
return type(s) == "string"
end
if RUN_ASSERTS then
assert(isString("s"))
assert(not isString(true))
end
local function isChar(c)
return isString(c) and string.len(c) == 1
end
if RUN_ASSERTS then
assert(isChar("s"))
assert(not isChar("xx"))
assert(not isChar(true))
end
local function isTableOfChars(t)
if not isTable(t) then
return false
end
for _key, ch in pairs(t) do
if not isChar(ch) then
return false
end
end
return true
end
if RUN_ASSERTS then
assert(isTableOfChars({}))
assert(isTableOfChars({"a", "b", "c"}))
assert(not isTableOfChars({"a", "b", "ccc"}))
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Language Helpers
local function isTableEmpty(t)
for _key, _val in pairs(t) do
return false
end
return true
end
if RUN_ASSERTS then
assert(isTableEmpty({}))
assert(not isTableEmpty({"a", "b"}))
end
local function tableSize(t)
if RUN_ASSERTS then
assert(isTable(t), "used tableSize with not an Table")
end
local count = 0
for _key, _val in pairs(t) do
count = count + 1
end
return count
end
if RUN_ASSERTS then
assert(tableSize({}) == 0)
assert(tableSize({"a", "b"}) == 2)
assert(tableSize({"a", "b", "c", "d", "e"}) == 5)
assert(tableSize({a = "a", b = "b"}) == 2)
end
local function strLen(s)
if RUN_ASSERTS then
assert(isString(s), "used strLen with not a String")
end
return string.len(s)
end
local function strConcat(s1, s2)
if RUN_ASSERTS then
assert(isString(s1), "strConcat argument s1 is not a String")
assert(isString(s2), "strConcat argument s2 is not a String")
end
return s1 .. s2
end
local function getCharFromString(s, idx)
if RUN_ASSERTS then
assert(isString(s), "getCharFromString argument s is not a String")
assert(isInteger(idx), "getCharFromString argument idx is not an Integer")
end
return string.sub(s, idx, idx)
end
if RUN_ASSERTS then
assert(getCharFromString("abc", 1) == "a")
assert(getCharFromString("abc", 2) == "b")
end
local function strJoin(tbl, delimiter)
if RUN_ASSERTS then
assert(isTable(tbl), "strJoin argument tbl is not a Table")
assert(isString(delimiter), "strJoin argument delimiter is not a String")
end
return table.concat(tbl, delimiter)
end
if RUN_ASSERTS then
assert(strJoin({"a", "b", "c"}, "") == "abc")
assert(strJoin({"a", "b", "c"}, "x") == "axbxc")
assert(strJoin({"a", "b", "c"}, "\n") == "a\nb\nc")
assert(strJoin({"a", "b", "c", "dd"}, "zz") == "azzbzzczzdd")
assert(strJoin({}, "z") == "")
assert(strJoin({}, "") == "")
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- String Operations
local function replaceWithinString(orig, startIdx, endIdx, replace)
local head = string.sub(orig, 1, startIdx - 1)
local tail = string.sub(orig, endIdx, -1)
return head .. replace .. tail
end
if RUN_ASSERTS then
assert(replaceWithinString("abc", 1, 3, "") == "c")
assert(replaceWithinString("abc", 1, 2, "x") == "xbc")
assert(replaceWithinString("abc", 1, 3, "x") == "xc")
assert(replaceWithinString("abcdef", 4, 26, "") == "abc")
end
local function repeatString(text, n)
return string.rep(text, n)
end
if RUN_ASSERTS then
assert(repeatString("a", 2) == "aa")
assert(repeatString("aa", 3) == "aaaaaa")
assert(repeatString("aa", 0) == "")
assert(repeatString("", 0) == "")
assert(repeatString("", 5) == "")
end
local function getLineEnding(text)
-- TODO: allow for "\r\n" as well as "\n" here
return "\n"
end
-- modified from penlight: https://tinyurl.com/37fqwxy8
local function splitLines(s)
if s == "" then
return {""}
end
local res = {}
local pos = 1
while true do
local line_end_pos = string.find(s, "[\r\n]", pos)
if not line_end_pos then
break
end
local line_end = string.sub(s, line_end_pos, line_end_pos)
if line_end == "\r" and string.sub(s, line_end_pos + 1, line_end_pos + 1) == "\n" then
line_end = "\r\n"
end
local line = string.sub(s, pos, line_end_pos - 1)
table.insert(res, line)
pos = line_end_pos + #line_end
end
if pos <= #s then
table.insert(res, string.sub(s, pos))
end
local len = strLen(s)
local lastCh = getCharFromString(s, len)
if lastCh == "\n" then
table.insert(res, "")
end
return res
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Stack Operations
local function isStackEmpty(t)
if RUN_ASSERTS then
assert(isTable(t), "used isStackEmpty with not a Table")
end
for _key, _val in pairs(t) do
return false
end
return true
end
if RUN_ASSERTS then
assert(isStackEmpty({}))
assert(not isStackEmpty({"a"}))
assert(not isStackEmpty({"a", "b"}))
end
local function peek(arr, idxFromBack)
idxFromBack = idxFromBack + 1
local maxIdx = tableSize(arr)
if (idxFromBack > maxIdx) then
return nil
end
return arr[maxIdx - idxFromBack + 1]
end
if RUN_ASSERTS then
assert(peek({"a"}, 0) == "a")
assert(peek({"a"}, 1) == nil)
assert(peek({"a", "b", "c"}, 0) == "c")
assert(peek({"a", "b", "c"}, 1) == "b")
assert(peek({"a", "b", "c"}, 5) == nil)
assert(peek({}, 0) == nil)
assert(peek({}, 1) == nil)
end
local function stackPop(s)
if RUN_ASSERTS then
assert(isTable(s), "used stackPop with not an Table")
end
return table.remove(s)
end
if RUN_ASSERTS then
assert(stackPop({"a"}) == "a")
assert(stackPop({"a", "b", "c"}) == "c")
local testTable1 = {"a", "b"}
assert(stackPop(testTable1) == "b")
assert(tableSize(testTable1) == 1)
assert(stackPop(testTable1) == "a")
assert(tableSize(testTable1) == 0)
stackPop(testTable1)
assert(tableSize(testTable1) == 0)
end
local function stackPush(s, itm)
if RUN_ASSERTS then
assert(isTable(s), "used stackPush with not an Table")
assert(isString(itm) or itm, "used stackPush without a second itm")
end
table.insert(s, itm)
return nil
end
if RUN_ASSERTS then
local testTable2 = {"a", "b"}
stackPush(testTable2, "c")
assert(tableSize(testTable2) == 3)
assert(peek(testTable2, 0) == "c")
assert(peek(testTable2, 1) == "b")
end
-- returns a new table with elements of tbl
-- startIdx and endIdx are both inclusive
local function sliceTable(tbl, startIdx, endIdx)
local newTable = {}
for idx, v in pairs(tbl) do
if idx >= startIdx and idx <= endIdx then
table.insert(newTable, v)
end
end
return newTable
end
if RUN_ASSERTS then
assert(strJoin(sliceTable({"a", "b", "c"}, 1, 1), "") == strJoin({"a"}, ""))
assert(strJoin(sliceTable({"a", "b", "c"}, 2, 2), "") == strJoin({"b"}, ""))
assert(strJoin(sliceTable({"a", "b", "c", "d", "e"}, 2, 3), "") == strJoin({"b", "c"}, ""))
assert(strJoin(sliceTable({"a", "b", "c", "d", "e"}, 3, 25), "") == strJoin({"c", "d", "e"}, ""))
assert(strJoin(sliceTable({}, 2, 3), "") == strJoin({}, ""))
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Options Structure
local function transformChange(change)
if not change then
return nil
end
local newLines = splitLines(change.newText)
local oldLines = splitLines(change.oldText)
-- single line case:
-- (defn foo| [])
-- ^ newEndX, newEndLineNo
-- +++
-- multi line case:
-- (defn foo
-- ++++
-- "docstring."
-- ++++++++++++++++
-- |[])
-- ++^ newEndX, newEndLineNo
local prevOldLine = peek(oldLines, 0)
local lastOldLineLen = strLen(prevOldLine)
local prevNewLine = peek(newLines, 0)
local lastNewLineLen = strLen(prevNewLine)
local carryOverOldX = 1 -- Lua ONE INDEX
if tableSize(oldLines) == 1 then
carryOverOldX = change.x
end
local oldEndX = carryOverOldX + lastOldLineLen
local carryOverNewX = 1 -- Lua ONE INDEX
if tableSize(newLines) == 1 then
carryOverNewX = change.x
end
local newEndX = carryOverNewX + lastNewLineLen
local newEndLineNo = change.lineNo + tableSize(newLines) - 1
return {
x = change.x,
lineNo = change.lineNo,
oldText = change.oldText,
newText = change.newText,
oldEndX = oldEndX,
newEndX = newEndX,
newEndLineNo = newEndLineNo,
lookupLineNo = newEndLineNo,
lookupX = newEndX
}
end
local function transformChanges(changes)
if tableSize(changes) == 0 then
return nil
else
local lines = {}
local changesLen = tableSize(changes)
local i = 1 -- Lua ONE INDEX
while i <= changesLen do
local change = transformChange(changes[i])
local line = lines[change.lookupLineNo]
if not line then
line = {}
lines[change.lookupLineNo] = line
end
line[change.lookupX] = change
i = i + 1
end
return lines
end
end
local function parseOptions(options)
if (not isTable(options)) then
options = {}
end
return {
changes = options.changes,
commentChars = options.commentChars,
cursorLine = options.cursorLine,
cursorX = options.cursorX,
forceBalance = options.forceBalance,
partialResult = options.partialResult,
prevCursorLine = options.prevCursorLine,
prevCursorX = options.prevCursorX,
returnParens = options.returnParens,
selectionStartLine = options.selectionStartLine
}
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Result Structure
local function initialParenTrail()
return {
lineNo = UINT_NULL,
startX = UINT_NULL,
endX = UINT_NULL,
openers = {},
clamped = {
startX = UINT_NULL,
endX = UINT_NULL,
openers = {}
}
}
end
local function getInitialResult(text, options, mode, smart)
local result = {
mode = mode,
smart = smart,
origText = text,
origCursorX = UINT_NULL,
origCursorLine = UINT_NULL,
inputLines = splitLines(text),
inputLineNo = 0, -- Lua ONE INDEX
inputX = 0, -- Lua ONE INDEX
lines = {},
lineNo = 0, -- Lua ONE INDEX
ch = "",
x = 0, -- Lua ONE INDEX
indentX = UINT_NULL,
parenStack = {},
tabStops = {},
parenTrail = initialParenTrail(),
parenTrails = {},
returnParens = false,
parens = {},
cursorX = UINT_NULL,
cursorLine = UINT_NULL,
prevCursorX = UINT_NULL,
prevCursorLine = UINT_NULL,
commentChars = {";"},
selectionStartLine = UINT_NULL,
changes = nil,
isInCode = true,
isEscaping = false,
isEscaped = false,
isInStr = false,
isInComment = false,
commentX = UINT_NULL,
quoteDanger = false,
trackingIndent = false,
skipChar = false,
success = false,
partialResult = false,
forceBalance = false,
maxIndent = UINT_NULL,
indentDelta = 0,
trackingArgTabStop = nil,
["error"] = {
name = nil,
message = nil,
lineNo = nil,
x = nil,
extra = {
name = nil,
lineNo = nil,
x = nil
}
},
errorPosCache = {}
}
-- merge user options if they are valid
if (options) then
if isInteger(options.cursorX) then
result.cursorX = options.cursorX
result.origCursorX = options.cursorX
end
if isInteger(options.cursorLine) then
result.cursorLine = options.cursorLine
result.origCursorLine = options.cursorLine
end
if isInteger(options.prevCursorX) then
result.prevCursorX = options.prevCursorX
end
if isInteger(options.prevCursorLine) then
result.prevCursorLine = options.prevCursorLine
end
if isInteger(options.selectionStartLine) then
result.selectionStartLine = options.selectionStartLine
end
if isTable(options.changes) then
result.changes = transformChanges(options.changes)
end
if isBoolean(options.partialResult) then
result.partialResult = options.partialResult
end
if isBoolean(options.forceBalance) then
result.forceBalance = options.forceBalance
end
if isBoolean(options.returnParens) then
result.returnParens = options.returnParens
end
if isChar(options.commentChars) then
result.commentChars = {options.commentChars}
end
if isTableOfChars(options.commentChars) then
result.commentChars = options.commentChars
end
end
return result
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Possible Errors
-- `result.error.name` is set to any of these
local ERROR_QUOTE_DANGER = "quote-danger"
local ERROR_EOL_BACKSLASH = "eol-backslash"
local ERROR_UNCLOSED_QUOTE = "unclosed-quote"
local ERROR_UNCLOSED_PAREN = "unclosed-paren"
local ERROR_UNMATCHED_CLOSE_PAREN = "unmatched-close-paren"
local ERROR_UNMATCHED_OPEN_PAREN = "unmatched-open-paren"
local ERROR_LEADING_CLOSE_PAREN = "leading-close-paren"
local ERROR_UNHANDLED = "unhandled"
local errorMessages = {}
errorMessages[ERROR_QUOTE_DANGER] = "Quotes must balanced inside comment blocks."
errorMessages[ERROR_EOL_BACKSLASH] = "Line cannot end in a hanging backslash."
errorMessages[ERROR_UNCLOSED_QUOTE] = "String is missing a closing quote."
errorMessages[ERROR_UNCLOSED_PAREN] = "Unclosed open-paren."
errorMessages[ERROR_UNMATCHED_CLOSE_PAREN] = "Unmatched close-paren."
errorMessages[ERROR_UNMATCHED_OPEN_PAREN] = "Unmatched open-paren."
errorMessages[ERROR_LEADING_CLOSE_PAREN] = "Line cannot lead with a close-paren."
errorMessages[ERROR_UNHANDLED] = "Unhandled error."
local function cacheErrorPos(result, errorName)
local e = {
lineNo = result.lineNo,
x = result.x,
inputLineNo = result.inputLineNo,
inputX = result.inputX
}
result.errorPosCache[errorName] = e
return e
end
local function createError(result, name)
local cache = result.errorPosCache[name]
local keyLineNo = "inputLineNo"
local keyX = "inputX"
if result.partialResult then
keyLineNo = "lineNo"
keyX = "x"
end
local lineNo = 0
local x = 0
if cache then
lineNo = cache[keyLineNo]
x = cache[keyX]
else
lineNo = result[keyLineNo]
x = result[keyX]
end
local err = {
parinferError = true,
name = name,
message = errorMessages[name],
lineNo = lineNo,
x = x
}
local opener = peek(result.parenStack, 0)
if name == ERROR_UNMATCHED_CLOSE_PAREN then
-- extra error info for locating the open-paren that it should've matched
local cache2 = result.errorPosCache[ERROR_UNMATCHED_OPEN_PAREN]
if cache2 or opener then
local lineNo2 = 0
local x2 = 0
if cache2 then
lineNo2 = cache2[keyLineNo]
x2 = cache2[keyX]
else
lineNo2 = opener[keyLineNo]
x2 = opener[keyX]
end
err.extra = {
name = ERROR_UNMATCHED_OPEN_PAREN,
lineNo = lineNo2,
x = x2
}
end
elseif name == ERROR_UNCLOSED_PAREN then
err.lineNo = opener[keyLineNo]
err.x = opener[keyX]
end
return err
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Line Operations
local function isCursorAffected(result, startIdx, endIdx)
if (result.cursorX == startIdx and result.cursorX == endIdx) then
return result.cursorX == 1 -- Lua ONE INDEX
end
return result.cursorX >= endIdx
end
local function shiftCursorOnEdit(result, lineNo, startIdx, endIdx, replaceTxt)
local oldLength = endIdx - startIdx
local newLength = strLen(replaceTxt)
local dx = newLength - oldLength
if
(dx ~= 0 and result.cursorLine == lineNo and result.cursorX ~= UINT_NULL and
isCursorAffected(result, startIdx, endIdx))
then
result.cursorX = result.cursorX + dx
end
end
local function replaceWithinLine(result, lineNo, startIdx, endIdx, replaceTxt)
local line = result.lines[lineNo]
local newLine = replaceWithinString(line, startIdx, endIdx, replaceTxt)
result.lines[lineNo] = newLine
shiftCursorOnEdit(result, lineNo, startIdx, endIdx, replaceTxt)
end
local function insertWithinLine(result, lineNo, idx, insert)
replaceWithinLine(result, lineNo, idx, idx, insert)
end
local function initLine(result)
result.x = 1 -- Lua ONE INDEX
result.lineNo = result.lineNo + 1
-- reset line-specific state
result.indentX = UINT_NULL
result.commentX = UINT_NULL
result.indentDelta = 0
result.errorPosCache[ERROR_UNMATCHED_CLOSE_PAREN] = nil
result.errorPosCache[ERROR_UNMATCHED_OPEN_PAREN] = nil
result.errorPosCache[ERROR_LEADING_CLOSE_PAREN] = nil
result.trackingArgTabStop = nil
result.trackingIndent = not result.isInStr
end
-- if the current character has changed, commit its change to the current line.
local function commitChar(result, origCh)
local ch = result.ch
local origChLength = strLen(origCh)
local chLength = strLen(ch)
if origCh ~= ch then
replaceWithinLine(result, result.lineNo, result.x, result.x + origChLength, ch)
result.indentDelta = result.indentDelta - origChLength - chLength
end
result.x = result.x + chLength
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Misc Util
local function clamp(val, minN, maxN)
if (minN ~= UINT_NULL) then
val = math.max(minN, val)
end
if (maxN ~= UINT_NULL) then
val = math.min(maxN, val)
end
return val
end
if RUN_ASSERTS then
assert(clamp(1, 3, 5) == 3)
assert(clamp(9, 3, 5) == 5)
assert(clamp(1, 3, UINT_NULL) == 3)
assert(clamp(5, 3, UINT_NULL) == 5)
assert(clamp(1, UINT_NULL, 5) == 1)
assert(clamp(9, UINT_NULL, 5) == 5)
assert(clamp(1, UINT_NULL, UINT_NULL) == 1)
end
-- concat the elements in t2 onto t1
-- returns a new table
local function concatTables(t1, t2)
local newTable = {}
for k, v in pairs(t1) do
table.insert(newTable, v)
end
for k, v in pairs(t2) do
table.insert(newTable, v)
end
return newTable
end
if RUN_ASSERTS then
assert(strJoin(concatTables({}, {}), "") == strJoin({}, ""))
assert(strJoin(concatTables({"a"}, {}), "") == strJoin({"a"}, ""))
assert(strJoin(concatTables({}, {"a"}), "") == strJoin({"a"}, ""))
assert(strJoin(concatTables({"a", "b", "c"}, {"d", "e"}), "") == strJoin({"a", "b", "c", "d", "e"}, ""))
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Character Predicates
local function isOpenParen(ch)
return ch == "{" or ch == "(" or ch == "["
end
local function isCloseParen(ch)
return ch == "}" or ch == ")" or ch == "]"
end
if RUN_ASSERTS then
assert(isOpenParen("(") == true)
assert(isOpenParen("]") == false)
assert(isCloseParen("}") == true)
assert(isCloseParen("a") == false)
end
local function isValidCloseParen(parenStack, ch)
if isStackEmpty(parenStack) then
return false
end
local lastOnStack = peek(parenStack, 0)
return lastOnStack.ch == MATCH_PAREN[ch]
end
local function isWhitespace(result)
local ch = result.ch
return (not result.isEscaped) and (ch == BLANK_SPACE or ch == DOUBLE_SPACE)
end
-- can this be the last code character of a list?
local function isClosable(result)
local ch = result.ch
local isCloser = isCloseParen(ch) and not result.isEscaped
return result.isInCode and not isWhitespace(result) and ch ~= "" and not isCloser
end
local function isCommentChar(ch, commentChars)
for _key, commentCh in pairs(commentChars) do
if ch == commentCh then
return true
end
end
return false
end
if RUN_ASSERTS then
assert(isCommentChar(";", {";"}))
assert(isCommentChar(";", {";", "#"}))
assert(isCommentChar("#", {";", "#"}))
assert(not isCommentChar("x", {";"}))
assert(not isCommentChar("", {";"}))
assert(not isCommentChar("#", {";", "a"}))
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Advanced Character Operations
local function checkCursorHolding(result)
local opener = peek(result.parenStack, 0)
local parent = peek(result.parenStack, 1)
local holdMinX = 1 -- Lua ONE INDEX
if parent then
holdMinX = parent.x + 1
end
local holdMaxX = opener.x
local holding = result.cursorLine == opener.lineNo and holdMinX <= result.cursorX and result.cursorX <= holdMaxX
local shouldCheckPrev = not result.changes and result.prevCursorLine ~= UINT_NULL
if shouldCheckPrev then
local prevHolding =
result.prevCursorLine == opener.lineNo and holdMinX <= result.prevCursorX and result.prevCursorX <= holdMaxX
if prevHolding and not holding then
error({releaseCursorHold = true})
end
end
return holding
end
local function trackArgTabStop(result, state)
if state == "space" then
if result.isInCode and isWhitespace(result) then
result.trackingArgTabStop = "arg"
end
elseif state == "arg" then
if not isWhitespace(result) then
local opener = peek(result.parenStack, 0)
opener.argX = result.x
result.trackingArgTabStop = nil
end
end
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Literal Character Events
local function onOpenParen(result)
if result.isInCode then
local opener = {
inputLineNo = result.inputLineNo,
inputX = result.inputX,
lineNo = result.lineNo,
x = result.x,
ch = result.ch,
indentDelta = result.indentDelta,
maxChildIndent = UINT_NULL
}
if result.returnParens then
opener.children = {}
opener.closer = {
lineNo = UINT_NULL,
x = UINT_NULL,
ch = ""
}
local parent1 = peek(result.parenStack, 0)
local parent2 = result.parens
if parent1 then
parent2 = parent1.children
end
stackPush(parent2, opener)
end
stackPush(result.parenStack, opener)
result.trackingArgTabStop = "space"
end
end
local function setCloser(opener, lineNo, x, ch)
opener.closer.lineNo = lineNo
opener.closer.x = x
opener.closer.ch = ch
end
local function onMatchedCloseParen(result)
local opener = peek(result.parenStack, 0)
if result.returnParens then
setCloser(opener, result.lineNo, result.x, result.ch)
end
result.parenTrail.endX = result.x + 1
stackPush(result.parenTrail.openers, opener)
if (result.mode == INDENT_MODE and result.smart and checkCursorHolding(result)) then
local origStartX = result.parenTrail.startX
local origEndX = result.parenTrail.endX
local origOpeners = result.parenTrail.openers
resetParenTrail(result, result.lineNo, result.x + 1)
result.parenTrail.clamped.startX = origStartX
result.parenTrail.clamped.endX = origEndX
result.parenTrail.clamped.openers = origOpeners
end
stackPop(result.parenStack)
result.trackingArgTabStop = nil
end
local function onUnmatchedCloseParen(result)
if (result.mode == PAREN_MODE) then
local trail = result.parenTrail
local inLeadingParenTrail = (trail.lineNo == result.lineNo) and (trail.startX == result.indentX)
local canRemove = result.smart and inLeadingParenTrail
if not canRemove then
error(createError(result, ERROR_UNMATCHED_CLOSE_PAREN))
end
elseif (result.mode == INDENT_MODE and not result.errorPosCache[ERROR_UNMATCHED_CLOSE_PAREN]) then
cacheErrorPos(result, ERROR_UNMATCHED_CLOSE_PAREN)
local opener = peek(result.parenStack, 0)
if opener then
local e = cacheErrorPos(result, ERROR_UNMATCHED_OPEN_PAREN)
e.inputLineNo = opener.inputLineNo
e.inputX = opener.inputX
end
end
result.ch = ""
end
local function onCloseParen(result)
if result.isInCode then
if isValidCloseParen(result.parenStack, result.ch) then
onMatchedCloseParen(result)
else
onUnmatchedCloseParen(result)
end
end
end
local function onTab(result)
if result.isInCode then
result.ch = DOUBLE_SPACE
end
end
local function onCommentChar(result)
if result.isInCode then
result.isInComment = true
result.commentX = result.x
result.trackingArgTabStop = nil
end
end
local function onNewline(result)
result.isInComment = false
result.ch = ""
end
local function onQuote(result)
if result.isInStr then
result.isInStr = false