-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.lua
More file actions
1670 lines (1553 loc) · 51.4 KB
/
Copy patheditor.lua
File metadata and controls
1670 lines (1553 loc) · 51.4 KB
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
#!/usr/bin/env lua
-- editor.lua -- piecetab-based terminal text editor (class skeleton)
-- usage: lua editor.lua [file]
package.cpath = package.cpath ..
";./lua/?.so;./lua/luajit/?.so;/opt/homebrew/lib/lua/5.5/?.so;/opt/homebrew/lib/lua/5.4/?.so"
package.path = package.path .. ";./lua/?.lua"
local pt = require("piecetab")
local cg = require("cellgrid")
local utf8 = require("lua-utf8")
local tf = require("termfeed")
local ok_ts, ts = pcall(require, "treesitter")
if not ok_ts then ts = nil end -- absent: hl off (pcall err msg is a string, not nil)
local lsp = require("lsp")
local luv = require("luv")
-- ================================================================
-- Section 0: Logging (writes to editor.log for debugging)
-- ================================================================
local logfile = nil
---@param fmt string
local function edlog(fmt, ...)
if not logfile then
local f = io.open("editor.log", "w")
if f then
f:setvbuf("line")
logfile = f
end
end
if logfile then
logfile:write(string.format(fmt, ...) .. "\n")
end
end
-- ================================================================
-- Section 1: Term class (terminal I/O via termfeed, not exported)
-- ================================================================
---@alias editor.Mode "normal"|"insert"|"command"|"visual"
---@alias editor.Key string
---@alias editor.KeymapFn fun(self: editor.Ed, key: editor.Key)
---@alias editor.CommandFn fun(self: editor.Ed, arg: string, bang: boolean)
--- @class editor.Term
---@field out {write: fun(o: table, s: string), flush: fun(o: table)}
---@field size_fn fun(): integer, integer
---@field tf termfeed.State
---@field esc_timeout integer
---@field s? string captured output (fake term in tests)
local Term = {}
-- method-style wrapper so Term:write/self.out.write(self.out, s) works
-- for both this and duck-typed outs (fake term in tests)
local IO = {
write = function(_, s) io.write(s) end,
flush = function() io.flush() end
}
do
Term.__index = Term
--- @param opts? table {out?, size?}
--- @return editor.Term
function Term.new(opts)
opts = opts or {}
local self = setmetatable({}, Term)
--- @type termfeed.State
self.tf = assert(tf.new())
self.tf:setflag(tf.FLAG_DELBS)
self.out = opts.out or IO
-- bare ESC: waitkey polls esc_timeout ms for a sequence prefix before
-- flushing it as a standalone ESC key (vim timeoutlen; -1 blocks forever)
self.esc_timeout = opts.esc_timeout or 50
self.size_fn = opts.size or function()
local r, c = cg.winsize(1)
if r and c then return r, c end
return 24, 80
end
return self
end
--- @param s string
function Term:write(s)
self.out.write(self.out, s)
end
function Term:flush()
self.out.flush(self.out)
end
--- @return integer rows, integer cols
function Term:size()
return self.size_fn()
end
--- @param row integer
--- @param col integer
function Term:move(row, col)
self:write(string.format("\27[%d;%dH", row, col))
end
--- Read one key, waiting up to `timeout` ms (nil = timed out, the
--- caller can run idle work). Defaults to the ESC prefix window.
--- @return string?
function Term:getkey(timeout)
if self.tf:waitkey(0, timeout or self.esc_timeout) ~= "KEY" then
return nil
end
return self.tf:format()
end
--- Enter alt screen + raw mode (main only; tests use fake term).
function Term:enter()
self:write("\27[?1049h\27[?25l")
self:flush()
self.tf:raw(0)
end
--- Leave raw mode, restore terminal.
function Term:leave()
self.tf:cooked()
self.tf:delete()
self:write("\27[?25h\27[2J\27[?1049l")
self:flush()
end
end
-- style codes
Term.REVERSE = "\27[7m"
Term.DIM = "\27[2m"
Term.RESET = "\27[0m"
-- attribute field tables (interned into grid style handles by sc)
local ATTR_DIM = { dim = true }
local ATTR_GRAY_BG = { bg = 237 }
local ATTR_KEYWORD = { fg = 207 }
local ATTR_STRING = { fg = 114 }
local ATTR_COMMENT = { fg = 245 }
local ATTR_FUNCTION = { fg = 81 }
local ATTR_NUMBER = { fg = 215 }
local ATTR_DIAG = { underline = true }
local ATTR_REVERSE = { reverse = true }
-- ================================================================
-- Section 2: Text/cursor pure functions
-- Char motion and column math here are C-module incubation
-- candidates (see notes/design_editor.md); keep them marked.
-- ================================================================
---@param byte integer
local function word_class(byte)
if byte >= 48 and byte <= 57 then return 1 end -- digit
if byte >= 65 and byte <= 90 then return 1 end -- upper
if byte >= 97 and byte <= 122 then return 1 end -- lower
if byte == 95 then return 1 end -- underscore
return 0
end
-- Move cursor by n characters (-1 = left, +1 = right). A successful
-- horizontal motion re-samples the vertical goal column (Neovim curswant).
---@param ed editor.Ed
---@param n integer
local function cursor_move_char(ed, n)
-- TODO(C): promote char motion to C (pt or new module)
local doc = ed.doc
local off = doc:offset()
if n < 0 and off <= 0 then return end
local buf = doc:buffer()
local saved = off
if n < 0 then
-- tail window [off-4, off+1): prev char lead + current lead
local s0 = math.max(off - 4, 0)
local p = utf8.offset(buf:read(s0, off - s0 + 1), -1, off - s0 + 1)
doc:seek("set", p - 1 + s0)
elseif n > 0 then
if off >= #buf then return end
-- 5 bytes cover a 4-byte char plus its successor's lead byte
local nxt = utf8.next(buf:read(off, 5), 1)
doc:seek("set", nxt and off + nxt - 1 or #buf)
end
-- restore if seek didn't move (boundary clamp)
if doc:offset() == saved and n > 0 and off < #buf then
doc:seek("set", off + 1)
end
if doc:offset() ~= saved then ed.goal = nil end
end
---@param ed editor.Ed
local function move_word_forward(ed)
local doc = ed.doc
local saved = doc:offset()
local lnum = doc:line()
doc:seek("line", lnum)
local line = doc:read("l") or ""
doc:seek("set", saved)
local col = doc:column()
edlog("w: saved=%d lnum=%d line=[%s](%d) col=%d",
saved, lnum, line, #line, col)
local len = #line
local i = col + 0
-- skip current word or space
if i < len then
local cls = word_class(line:byte(i + 1))
while i < len and word_class(line:byte(i + 1)) == cls do i = i + 1 end
-- skip whitespace
while i < len and word_class(line:byte(i + 1)) == 0 and line:byte(i + 1) == 32 do i = i + 1 end
end
doc:seek("cur", i - col)
edlog("w result: seek cur %d", i - col)
if doc:offset() ~= saved then ed.goal = nil end
end
---@param ed editor.Ed
local function move_word_backward(ed)
local doc = ed.doc
local saved = doc:offset()
local lnum = doc:line()
doc:seek("line", lnum)
local line = doc:read("l") or ""
doc:seek("set", saved)
local col = doc:column()
local i = col - 1
-- skip whitespace
while i > 0 and line:byte(i + 1) == 32 do i = i - 1 end
if i >= 0 then
local cls = word_class(line:byte(i + 1))
while i >= 0 and word_class(line:byte(i + 1)) == cls do i = i - 1 end
end
doc:seek("cur", (i + 1) - col)
if doc:offset() ~= saved then ed.goal = nil end
end
-- Rendering helpers
-- helper: end-of-text column for line (excludes trailing \n)
---@param ed editor.Ed
---@param lnum integer
local function line_endcol(ed, lnum)
local llen = ed.doc:linelen(lnum)
if llen > 0 and lnum < ed.doc:breaks() - 1 then llen = llen - 1 end
return llen
end
-- display column -> byte offset within given line (clamp to char boundary)
---@param doc piecetab.Doc
---@param lnum integer
---@param dcol integer
---@param grid cellgrid.Grid
local function dcol_to_byte(doc, lnum, dcol, grid)
local saved = doc:offset()
doc:seek("line", lnum)
local text = doc:read("l") or ""
doc:seek("set", saved)
return grid:byte(text, dcol)
end
-- Truncate text to fit a display width budget (UTF-8 aware, whole chars).
---@param text string
---@param maxw integer
---@return string
local function text_trunc(text, maxw)
if utf8.width(text) <= maxw then return text end
local w, i = 0, 1
while i <= #text do
local nxt = utf8.next(text, i) or #text + 1
local cw = utf8.width(text, i, nxt - 1) or 1
if w + cw > maxw then break end
w, i = w + cw, nxt
end
return text:sub(1, i - 1)
end
-- Move cursor vertically by dl lines, preserving the screen column
-- (injected text counts; Neovim semantics). The goal column (Neovim
-- curswant) survives the EOL clamp: once a long enough line is reached,
-- the cursor re-lands on it. Horizontal motions re-sample it.
---@param ed editor.Ed
---@param dl integer
local function move_vert(ed, dl)
local doc = ed.doc
local lnum = doc:line()
local nlnum = lnum + dl
if nlnum < 0 or nlnum >= doc:breaks() then return end
local scol = ed.goal or ed:vtext_dcol(lnum, doc:column(),
ed.mode == "INSERT")
ed.goal = scol
doc:seek("line", nlnum)
doc:seek("cur", dcol_to_byte(doc, nlnum,
ed:screen_to_text_dcol(nlnum, scol), ed.grid))
end
-- Open a new line: dir > 0 below (o), dir < 0 above (O); enter INSERT
---@param self editor.Ed
---@param dir integer
local function open_line(self, dir)
self.doc:seek("line", self.doc:line())
if dir > 0 then
self.doc:seek("cur", line_endcol(self, self.doc:line()))
end
self:docedit(0, "\n")
if dir < 0 then self.doc:seek("cur", -1) end
self.mode = "INSERT"
end
-- ================================================================
-- Section 3: Highlight module (style compositor + tree-sitter)
-- ================================================================
-- Style compositor: interns attr-field tables to unique handles. Cellgrid
-- treats style ids as opaque handles; the compositor owns the attr ->
-- handle -> CSI conversion. Field values: fg/bg = 256-color index or
-- {r,g,b} table; boolean keys (bold/underline/...) = set attribute.
--- @class editor.Sc
--- @field by_attr table<string, integer>
--- @field attr_by table<integer, table>
--- @field next_id integer
local sc = {}
local SGR_ATTR = {
bold = 1, dim = 2, italic = 3, underline = 4, reverse = 7,
}
do
sc.__index = sc
--- @return editor.Sc
function sc.new()
local self = setmetatable({ by_attr = {}, attr_by = {}, next_id = 0 }, sc)
self:intern({}) -- style 0 = default (empty) attr
return self
end
-- Canonical key: sorted "k:v" parts; booleans as bare "k"; {r,g,b} as
-- "k:rgb(r,g,b)". Nil/false fields are unset and skipped.
--- @param attr table
--- @return string
local function canon(attr)
local parts = {}
for k, v in pairs(attr) do
if v then
if type(v) == "table" then
parts[#parts + 1] = k .. ":rgb(" .. v.r .. "," .. v.g .. "," .. v.b .. ")"
elseif v ~= true then
parts[#parts + 1] = k .. ":" .. tostring(v)
else
parts[#parts + 1] = k
end
end
end
table.sort(parts)
return table.concat(parts, ",")
end
-- Intern an attr table to a unique handle; identical attrs share one.
--- @param attr table
--- @return integer
function sc:intern(attr)
local key = canon(attr)
local id = self.by_attr[key]
if id then return id end
id = self.next_id
self.next_id = id + 1
self.by_attr[key] = id
self.attr_by[id] = attr
return id
end
-- Inverse lookup: handle -> attr table (compositor-owned, do not mutate).
--- @param id integer
--- @return table
function sc:attr(id)
return self.attr_by[id]
end
-- SGR escape for a handle: reset + attribute codes (diff emits this on
-- style change, so each entry must be a full state).
--- @param id integer
--- @return string?
function sc:csi(id)
local a = self.attr_by[id]
if not a then return nil end
local codes = {}
for k, v in pairs(a) do
if v then
if k == "fg" or k == "bg" then
local pre = (k == "fg") and "38" or "48"
if type(v) == "table" then
codes[#codes + 1] = pre .. ";2;" .. v.r .. ";" .. v.g .. ";" .. v.b
else
codes[#codes + 1] = pre .. ";5;" .. v
end
else
local n = SGR_ATTR[k]
if n then codes[#codes + 1] = tostring(n) end
end
end
end
if #codes == 0 then return "\27[0m" end
table.sort(codes)
return "\27[0m\27[" .. table.concat(codes, ";") .. "m"
end
end
local hl = {}
-- file extension -> language name (nil = no highlighting)
---@param filename string?
---@return string?
local function ext_lang(filename)
if not filename then return nil end
local ext = filename:match("%.([%w_]+)$")
if ext == "c" or ext == "h" then return "c" end
if ext == "lua" then return "lua" end
return nil
end
-- LSP server command for a file (nil = no server available). PT_LSP_CMD
-- overrides the built-in mapping (space-split argv).
---@param filename string?
---@return string[]?
local function lsp_cmd(filename)
local over = os.getenv("PT_LSP_CMD")
if over and #over > 0 then
local argv = {}
for w in over:gmatch("%S+") do argv[#argv + 1] = w end
return argv
end
if ext_lang(filename) == "c" then return { "clangd" } end
if ext_lang(filename) == "lua" then return { "lua-language-server" } end
return nil
end
-- Minimal highlights subsets (keyword/string/comment/function).
-- NB: primitive types (int/char/void) are internal tokens of primitive_type,
-- not matchable as string literals; match the node type instead.
local HL_QUERIES = {
c = [[
(comment) @comment
(string_literal) @string
(primitive_type) @keyword
"break" @keyword
"case" @keyword
"const" @keyword
"continue" @keyword
"default" @keyword
"do" @keyword
"else" @keyword
"enum" @keyword
"extern" @keyword
"for" @keyword
"goto" @keyword
"if" @keyword
"inline" @keyword
"register" @keyword
"restrict" @keyword
"return" @keyword
"sizeof" @keyword
"static" @keyword
"struct" @keyword
"switch" @keyword
"typedef" @keyword
"union" @keyword
"volatile" @keyword
"while" @keyword
(function_definition
declarator: (function_declarator
declarator: (identifier) @function))
]],
lua = [[
(comment) @comment
(string) @string
"and" @keyword
(break_statement) @keyword
"do" @keyword
"else" @keyword
"elseif" @keyword
"end" @keyword
(false) @keyword
"for" @keyword
"function" @keyword
"goto" @keyword
"if" @keyword
"in" @keyword
"local" @keyword
(nil) @keyword
"not" @keyword
"or" @keyword
"repeat" @keyword
"return" @keyword
"then" @keyword
(true) @keyword
"until" @keyword
"while" @keyword
(function_call
name: (identifier) @function)
]],
}
local HL_ATTRS = {
comment = ATTR_COMMENT,
string = ATTR_STRING,
keyword = ATTR_KEYWORD,
["function"] = ATTR_FUNCTION,
}
-- LSP semantic tokenType names -> attrs (unknown names ignored; clangd
-- duplicate legend names map by name, same name -> same attr). diag is
-- the fallback underline attr (Client uses attrmap.diag when set).
local LSP_ATTRS = {
comment = ATTR_COMMENT,
string = ATTR_STRING,
keyword = ATTR_KEYWORD,
number = ATTR_NUMBER,
["function"] = ATTR_FUNCTION,
method = ATTR_FUNCTION,
diag = ATTR_DIAG,
}
--- Create a highlighter for a language ("c"/"lua"), nil if unsupported.
function hl.new(ed, lang)
if not ts then return nil end
local qsrc = HL_QUERIES[lang]
if not qsrc then return nil end
local langobj = ts.require(lang)
if not langobj then return nil end
local parser = ts.parser.new()
parser.language = langobj
local self = {
ed = ed,
parser = parser,
query = langobj:query(qsrc),
tree = nil,
dirty = true
}
return setmetatable(self, { __index = hl })
end
--- Reset tree (whole-reparse on next request). Used after undo/redo/:e.
function hl:reset()
self.tree = nil
self.dirty = true
end
--- Notify an edit: translate the tree, defer parse to next request.
function hl:notify_edit(start, old_len, new_len)
if self.tree then
local doc = self.ed.doc
local function pos(off)
doc:seek("set", off)
return doc:line() + 1, doc:column() + 1 -- 1-based
end
local srow, scol = pos(start)
local orow, ocol = pos(start + old_len)
local nrow, ncol = pos(start + new_len)
self.tree:edit(start + 1, start + old_len + 1, start + new_len + 1,
srow, scol, orow, ocol, nrow, ncol)
end
self.dirty = true
end
--- Parse if dirty. Content via doc:dump() (includes uncommitted edits;
-- doc:buffer() is committed-version only).
function hl:ensure()
if not self.dirty then return end
self.tree = self.parser:parse(self.tree, self.ed.doc:dump())
self.dirty = false
end
--- Query spans for a byte range: {offset, length, attr} (0-based offsets).
function hl:query_region(start, endoff)
self:ensure()
if not self.tree then return {} end
local c = self.query:exec(self.tree.root)
c:set_byte_range(start + 1, endoff)
local attrmap, spans = HL_ATTRS, {}
while true do
local ci = c:next_capture()
if not ci then break end
local node = c[ci]
local _, cid = c:captures(ci)
local attr = attrmap[self.query:capture_name_for_id(cid)]
if attr then
spans[#spans + 1] = {
offset = node.start_byte - 1,
length = node.end_byte - node.start_byte,
attr = attr
}
end
end
return spans
end
-- Fold layered writer spans into one attr span list. Higher layers
-- override keys set on lower ones (key-level partial merge); unset keys
-- pass through. Input/output: {offset, length, attr} (0-based).
--- @param layers table array of span arrays, low to high
--- @param start integer
--- @param endoff integer (exclusive)
--- @return table
local function merge_layers(layers, start, endoff)
local bounds = {}
for _, spans in ipairs(layers) do
for _, sp in ipairs(spans) do
bounds[#bounds + 1] = sp.offset
bounds[#bounds + 1] = sp.offset + sp.length
end
end
table.sort(bounds)
local out, lo = {}, start
local function fold(hi)
local attr = {}
for _, spans in ipairs(layers) do
for _, sp in ipairs(spans) do
if sp.offset <= lo and lo < sp.offset + sp.length then
for k, v in pairs(sp.attr) do
if v then attr[k] = v end
end
end
end
end
out[#out + 1] = { offset = lo, length = hi - lo, attr = attr }
end
for _, hi in ipairs(bounds) do
if hi <= lo then
-- duplicate boundary, skip
elseif hi >= endoff then
fold(endoff)
lo = endoff
break
else
fold(hi)
lo = hi
end
end
if lo < endoff then fold(endoff) end
return out
end
-- Piece-boundary writer (pull mode, no cache): scan all pieces, alternate
-- gray background on even pieces (first piece plain) to visualize
-- piecetab layout on screen.
--- @param doc piecetab.Doc
--- @param start integer
--- @param endoff integer (exclusive)
--- @return table
local function piece_spans(doc, start, endoff)
local spans, odd = {}, false
doc:seek("set", 0)
local len = doc:piece("len")
while len > 0 do
local off = doc:offset()
if odd and off + len > start and off < endoff then
spans[#spans + 1] = {
offset = math.max(off, start),
length = math.min(off + len, endoff) - math.max(off, start),
attr = ATTR_GRAY_BG,
}
end
odd = not odd
len = doc:piece("next")
end
return spans
end
-- Charwise visual selection [s, e): inclusive of both anchor and cursor
-- characters (vim semantics) — e = cursor char end, s = min char start.
-- Cursor always sits on a char start, so s is a plain min of the two.
--- @param doc piecetab.Doc
--- @param sel integer? selection anchor (byte offset)
--- @param cur integer cursor byte offset
--- @return integer, integer
local function sel_range(doc, sel, cur)
if not sel then return cur, cur end
local s, e = sel, cur
if sel > cur then s, e = cur, sel end
local tail = doc:buffer():read(e, 4)
local nxt = #tail > 0 and utf8.next(tail, 1)
return s, nxt and e + nxt - 1 or e
end
-- Visual-selection writer (pull mode, no cache): charwise selection
-- [s, e) reverse-highlighted where it intersects the visible region.
-- Top layer in render. Cursor passed in: render moves the doc cursor
-- around (piece scan), so doc:offset() is unreliable here.
--- @param doc piecetab.Doc
--- @param sel integer? selection anchor (byte offset)
--- @param cur integer cursor byte offset
--- @param start integer
--- @param endoff integer (exclusive)
--- @return table
local function visual_spans(doc, sel, cur, start, endoff)
local s, e = sel_range(doc, sel, cur)
local lo = math.max(s, start)
local hi = math.min(e, endoff)
if hi <= lo then return {} end
return { { offset = lo, length = hi - lo, attr = ATTR_REVERSE } }
end
--- @param spans table array of {offset, length, style}
--- @param line_start integer byte offset of line start
--- @param line_end integer byte offset of line end (exclusive)
--- @return table array of {start=1-based byte, len, style}
function hl.line_segments(spans, line_start, line_end)
local segs = {}
for _, sp in ipairs(spans) do
local r_end = sp.offset + sp.length
if sp.offset < line_end and r_end > line_start then
local s = math.max(sp.offset, line_start) - line_start + 1
local e = math.min(r_end, line_end) - line_start
if e >= s then
segs[#segs + 1] = { start = s, len = e - s + 1, style = sp.style }
end
end
end
return segs
end
-- Single-pass line render: walk clusters via g:next, switch style at
-- segment boundaries, batch same-style text into g:putslice (tabs are
-- expanded inside the grid). Returns absolute column (0-based) after
-- the rendered text.
---@param g cellgrid.Grid
---@param row integer
---@param col integer
---@param text string
---@param segs table
---@param hints table? sorted by dcol: {dcol, text, style} — injected
--- into the render stream (virt_text, never interned)
local function render_line(g, row, col, text, segs, hints)
local batch_start = 1
local cur_byte = 1
local cur_style = 0
local seg_idx = 1
local hint_idx = 1
local dc = 0
local hint_w = 0 -- injected hint width (overlay: not part of text col)
local ts = g:tabstop()
local function style_at(b)
while seg_idx <= #segs do
local s = segs[seg_idx]
if b >= s.start and b < s.start + s.len then
return s.style or 0
end
if b < s.start then break end
seg_idx = seg_idx + 1
end
return 0
end
-- flush [batch_start, cur_byte) as same-style putslice spans. Tabs
-- are expanded separately on the TEXT column (cursor math is text
-- based): putslice would align tabs to the render column, which
-- includes injected hints.
local function flush()
if batch_start < cur_byte then
local pos = batch_start
while pos < cur_byte do
local t = text:find("\t", pos, true)
if not t or t >= cur_byte then
dc = g:putslice(row, col + dc, cur_style, text,
pos, cur_byte - 1) - col
break
end
if t > pos then
dc = g:putslice(row, col + dc, cur_style, text,
pos, t - 1) - col
end
local ts = g:tabstop()
local n = ts - (dc - hint_w) % ts
local sc = col + dc
g:fill(row, sc, sc + n, 32, cur_style)
dc = dc + n
pos = t + 1
end
batch_start = cur_byte
end
end
local function flush_hints(dcol)
while hints and hint_idx <= #hints and hints[hint_idx].dcol <= dcol do
flush() -- write the text before the hint position first
local h = hints[hint_idx]
dc = g:putslice(row, col + dc, h.style, h.text) - col
hint_w = hint_w + g:cols(h.text)
hint_idx = hint_idx + 1
end
end
for byte, dcol in g:next(text) do
cur_byte = byte
flush_hints(dcol)
local st = style_at(byte)
if st ~= cur_style then
flush(); cur_style = st
end
end
cur_byte = #text + 1
flush()
flush_hints(g:cols(text)) -- end-of-line column
return col + dc
end
-- ================================================================
-- Section 4: Ed class
-- ================================================================
--- @class editor.Ed
---@field doc piecetab.Doc document buffer (undo history + linecache)
---@field hl table? syntax highlighter (tree-sitter), nil = no highlight
---@field filename string?
---@field mode string "NORMAL"|"INSERT"|"COMMAND"|"VISUAL"
---@field cmdline string
---@field msg string
---@field saved_vid integer
---@field pending_key string?
---@field goal integer? vertical goal column (Neovim curswant), nil = sample
---@field scroll_line integer
---@field log fun(fmt: string, ...: any)
---@field done boolean
---@field lsp lsp.Client? LSP client (nil = off)
---@field term editor.Term
---@field grid cellgrid.Grid
---@field keymaps table<string, table<string, fun(self: editor.Ed, key: string)>>
---@field commands table<string, fun(self: editor.Ed, arg?: string, bang?: boolean)>
---@field sc editor.Sc style compositor (attr -> handle intern)
---@field styles table<string, integer> pre-interned style handles
---@field show_pieces boolean piece-boundary visualization layer
---@field sel_start integer? visual-mode selection anchor (byte offset)
---@field clip string? unnamed register (yank buffer)
---@field vtexts table<integer, table<integer, {dcol: integer, text: string, style?: integer}>?> injected display text per line, ascending dcol
local Ed = {}
-- forward declaration: filled in Section 5 (dispatch reads it via upvalue)
local mode_dispatch = {}
-- Execute pending ":" cmdline: parse name/bang/arg, dispatch registered
-- :command; unregistered name sets msg "Unknown: :" .. line
local function exec_command(self)
self.mode = "NORMAL"
local line = self.cmdline
self.cmdline = ""
local name, bang, arg = line:match("^(%a+)(!?)(.*)")
local fn = name and self.commands[name]
if fn then
fn(self, arg:match("^%s*(.*)"), bang == "!")
else
self.msg = "Unknown: :" .. line
end
end
-- built-in normal keymaps (per-instance, called from Ed.new)
local function install_normal_keys(self)
local n = self.keymaps.normal
n.h = function(ed) cursor_move_char(ed, -1) end
n.l = function(ed) cursor_move_char(ed, 1) end
n.j = function(ed) move_vert(ed, 1) end
n.k = function(ed) move_vert(ed, -1) end
n.w = function(ed) move_word_forward(ed) end
n.b = function(ed) move_word_backward(ed) end
n["0"] = function(ed) ed.goal = nil; ed.doc:seek("line", ed.doc:line()) end
n["$"] = function(ed)
ed.goal = nil
local lnum = ed.doc:line()
ed.doc:seek("line", lnum)
local text = ed.doc:read("l") or ""
ed.doc:seek("line", lnum) -- read advanced past the line; rewind
if #text > 0 then
-- vim: stop on the last char, not after it (multi-byte aware)
ed.doc:seek("cur", utf8.offset(text, 0, #text) - 1) -- last char start
end
end
n.gg = function(ed) ed.goal = nil; ed.doc:seek("line", 0) end
n.G = function(ed) ed.goal = nil
ed.doc:seek("line", ed.doc:breaks() - 1)
end
n.x = function(ed)
ed:docedit(1, ""); ed.doc:commit()
end
n.dd = function(ed)
local lnum = ed.doc:line()
local llen = ed.doc:linelen(lnum)
ed.doc:seek("line", lnum)
ed:docedit(llen, "")
ed.doc:commit()
end
n.i = function(ed) ed.mode = "INSERT" end
n.a = function(ed)
cursor_move_char(ed, 1); ed.mode = "INSERT"
end
n.o = function(ed) open_line(ed, 1) end
n.O = function(ed) open_line(ed, -1) end
-- jump doc versions (undo/redo), feed the change hunks to the LSP
-- as sequential edits (incremental sync instead of a full didChange)
local function switch_sync(ed, name)
local changes
if ed.lsp then
changes = {}
ed.doc[name](ed.doc, function(off, del, text)
changes[#changes + 1] = { off = off, del = del, text = text }
end)
else
ed.doc[name](ed.doc)
end
if ed.hl then ed.hl:reset() end
if ed.lsp then ed.lsp:on_switch(changes) end
end
n.u = function(ed) switch_sync(ed, "undo") end
n.p = function(ed)
if not ed.clip then return end
ed:docedit(0, ed.clip)
ed.doc:commit()
end
n.v = function(ed)
ed.sel_start = ed.doc:offset()
ed.mode = "VISUAL"
end
n["<C-r>"] = function(ed) switch_sync(ed, "redo") end
n["<C-l>"] = function(ed) ed.grid:clear() end
n[":"] = function(ed)
ed.mode = "COMMAND"; ed.cmdline = ""
end
n["<Up>"] = n.k
n["<Down>"] = n.j
n["<Left>"] = n.h
n["<Right>"] = n.l
end
-- built-in insert handlers (registered via install_insert_keys)
local function ins_escape(self)
self.mode = "NORMAL"
self.doc:commit()
local off = self.doc:offset()
if off > 0 and self.doc:buffer():read(off - 1, 1) ~= "\n" then
cursor_move_char(self, -1)
end
self.msg = ""
end
local function ins_backspace(self)
local off = self.doc:offset()
if off > 0 then
-- tail window [off-4, off+1): prev char lead + current lead
local buf = self.doc:buffer()
local s0 = math.max(off - 4, 0)
local p = utf8.offset(buf:read(s0, off - s0 + 1), -1, off - s0 + 1)
local prev = p - 1 + s0
self.doc:seek("set", prev)
self:docedit(off - prev, "")
end
end
local function ins_delete(self)
local off = self.doc:offset()
local buf = self.doc:buffer()
if off < #buf then
-- 5 bytes cover a 4-byte char plus its successor's lead byte
local nxt = utf8.next(buf:read(off, 5), 1)
self:docedit(nxt and nxt - 1 or #buf - off, "")
end
end
-- built-in insert keymaps (per-instance, called from Ed.new)
local function install_insert_keys(self)
local i = self.keymaps.insert
i["<Escape>"] = ins_escape
i["<Backspace>"] = ins_backspace
i["<Delete>"] = ins_delete
i["<Enter>"] = function(ed) ed:docedit(0, "\n") end
i["<Tab>"] = function(ed) ed:docedit(0, "\t") end
i["<C-c>"] = function(ed)
ed.mode = "NORMAL"
ed.msg = ""
end
i["<Up>"] = function(ed) move_vert(ed, -1) end
i["<Down>"] = function(ed) move_vert(ed, 1) end
i["<Left>"] = function(ed) cursor_move_char(ed, -1) end
i["<Right>"] = function(ed) cursor_move_char(ed, 1) end
i["<Home>"] = function(ed) ed.goal = nil
ed.doc:seek("line", ed.doc:line()) end
i["<End>"] = function(ed)
ed.goal = nil
local lnum = ed.doc:line()
ed.doc:seek("line", lnum)
ed.doc:seek("cur", line_endcol(ed, lnum))
end
i["<PageUp>"] = function(ed)
local rows = ed.term:size()
for _ = 1, rows - 2 do move_vert(ed, -1) end
end
i["<PageDown>"] = function(ed)
local rows = ed.term:size()
for _ = 1, rows - 2 do move_vert(ed, 1) end
end
end
-- built-in visual keymaps (per-instance, called from Ed.new)
local function install_visual_keys(self)