init.lua 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. -- Lumacs Configuration File
  2. -- This file is executed on startup and allows you to customize keybindings,
  3. -- create commands, and extend the editor with Lua.
  4. print("Loading init.lua...")
  5. -- ============================================================================
  6. -- MODE SYSTEM (Emacs-style Major and Minor Modes)
  7. -- ============================================================================
  8. -- Mode registries
  9. local major_modes = {}
  10. local minor_modes = {}
  11. -- Active modes per buffer (keyed by buffer name)
  12. local buffer_major_modes = {}
  13. local buffer_minor_modes = {}
  14. -- Define a major mode
  15. function define_major_mode(name, config)
  16. major_modes[name] = {
  17. name = name,
  18. file_patterns = config.file_patterns or {},
  19. setup = config.setup or function() end,
  20. cleanup = config.cleanup or function() end,
  21. highlight = config.highlight or nil,
  22. keybindings = config.keybindings or {},
  23. comment_syntax = config.comment_syntax or "--",
  24. }
  25. print(string.format("[Mode] Registered major mode: %s", name))
  26. end
  27. -- Define a minor mode
  28. function define_minor_mode(name, config)
  29. minor_modes[name] = {
  30. name = name,
  31. setup = config.setup or function() end,
  32. cleanup = config.cleanup or function() end,
  33. keybindings = config.keybindings or {},
  34. global = config.global or false, -- If true, applies to all buffers
  35. }
  36. print(string.format("[Mode] Registered minor mode: %s", name))
  37. end
  38. -- Activate a major mode for the current buffer
  39. function activate_major_mode(mode_name)
  40. local buf = editor.buffer
  41. local buf_name = buf:name()
  42. local mode = major_modes[mode_name]
  43. if not mode then
  44. message("Unknown major mode: " .. mode_name)
  45. return false
  46. end
  47. -- Deactivate current major mode if any
  48. if buffer_major_modes[buf_name] then
  49. deactivate_major_mode()
  50. end
  51. print(string.format("[Mode] Activating major mode '%s' for buffer '%s'", mode_name, buf_name))
  52. -- Store active mode
  53. buffer_major_modes[buf_name] = mode_name
  54. -- Set up event handler for auto-highlighting
  55. if mode.highlight then
  56. buf:on_buffer_event(function(event_data)
  57. local current_buf = editor.buffer
  58. if event_data.event == lumacs.BufferEvent.Loaded or
  59. event_data.event == lumacs.BufferEvent.LanguageChanged then
  60. mode.highlight()
  61. print(string.format("[Mode] Auto-highlighted buffer with %s", mode_name))
  62. end
  63. end)
  64. -- Highlight immediately
  65. mode.highlight()
  66. end
  67. -- Apply mode-specific keybindings (these are temporary for this buffer)
  68. for key, func in pairs(mode.keybindings) do
  69. bind_key(key, func)
  70. end
  71. -- Run setup function
  72. mode.setup()
  73. message(string.format("Major mode: %s", mode_name))
  74. return true
  75. end
  76. -- Deactivate current major mode
  77. function deactivate_major_mode()
  78. local buf = editor.buffer
  79. local buf_name = buf:name()
  80. local mode_name = buffer_major_modes[buf_name]
  81. if not mode_name then
  82. return
  83. end
  84. local mode = major_modes[mode_name]
  85. if mode and mode.cleanup then
  86. mode.cleanup()
  87. end
  88. buffer_major_modes[buf_name] = nil
  89. print(string.format("[Mode] Deactivated major mode '%s'", mode_name))
  90. end
  91. -- Toggle a minor mode
  92. function toggle_minor_mode(mode_name)
  93. local buf = editor.buffer
  94. local buf_name = buf:name()
  95. local mode = minor_modes[mode_name]
  96. if not mode then
  97. message("Unknown minor mode: " .. mode_name)
  98. return
  99. end
  100. -- Initialize minor modes table for this buffer
  101. if not buffer_minor_modes[buf_name] then
  102. buffer_minor_modes[buf_name] = {}
  103. end
  104. local is_active = buffer_minor_modes[buf_name][mode_name]
  105. if is_active then
  106. -- Deactivate
  107. if mode.cleanup then
  108. mode.cleanup()
  109. end
  110. buffer_minor_modes[buf_name][mode_name] = nil
  111. message(string.format("Minor mode disabled: %s", mode_name))
  112. else
  113. -- Activate
  114. buffer_minor_modes[buf_name][mode_name] = true
  115. if mode.setup then
  116. mode.setup()
  117. end
  118. message(string.format("Minor mode enabled: %s", mode_name))
  119. end
  120. end
  121. -- Auto-detect and activate major mode based on file extension
  122. function auto_activate_major_mode()
  123. local buf = editor.buffer
  124. local buf_name = buf:name()
  125. -- Try to match file pattern
  126. for mode_name, mode in pairs(major_modes) do
  127. for _, pattern in ipairs(mode.file_patterns) do
  128. if string.match(buf_name, pattern) then
  129. activate_major_mode(mode_name)
  130. return
  131. end
  132. end
  133. end
  134. -- No match, use fundamental mode (default)
  135. print(string.format("[Mode] No major mode matched for '%s', using fundamental-mode", buf_name))
  136. end
  137. -- Get current major mode name
  138. function current_major_mode()
  139. local buf = editor.buffer
  140. local buf_name = buf:name()
  141. return buffer_major_modes[buf_name] or "fundamental-mode"
  142. end
  143. -- ============================================================================
  144. -- MAJOR MODES
  145. -- ============================================================================
  146. -- Lua Mode
  147. define_major_mode("lua-mode", {
  148. file_patterns = {"%.lua$"},
  149. comment_syntax = "--",
  150. highlight = function()
  151. local buf = editor.buffer
  152. buf:clear_styles()
  153. -- Keywords to highlight
  154. local keywords = {
  155. "function", "local", "end", "if", "then", "else", "elseif",
  156. "for", "while", "do", "return", "break", "and", "or", "not",
  157. "true", "false", "nil", "in", "repeat", "until"
  158. }
  159. -- Highlight each line
  160. for line_num = 0, buf:line_count() - 1 do
  161. local line_text = buf:line(line_num)
  162. -- Highlight keywords
  163. for _, keyword in ipairs(keywords) do
  164. local start_pos = 1
  165. while true do
  166. local pattern = "%f[%w]" .. keyword .. "%f[%W]"
  167. local pos = string.find(line_text, pattern, start_pos)
  168. if not pos then break end
  169. local range = lumacs.Range(
  170. lumacs.Position(line_num, pos - 1),
  171. lumacs.Position(line_num, pos + #keyword - 1)
  172. )
  173. buf:set_style(range, lumacs.TextAttribute(lumacs.ColorType.Keyword, 0))
  174. start_pos = pos + #keyword
  175. end
  176. end
  177. -- Highlight strings
  178. local start_pos = 1
  179. while true do
  180. local quote_start = string.find(line_text, '"', start_pos, true)
  181. if not quote_start then break end
  182. local quote_end = string.find(line_text, '"', quote_start + 1, true)
  183. if not quote_end then break end
  184. local range = lumacs.Range(
  185. lumacs.Position(line_num, quote_start - 1),
  186. lumacs.Position(line_num, quote_end)
  187. )
  188. buf:set_style(range, lumacs.TextAttribute(lumacs.ColorType.String, 0))
  189. start_pos = quote_end + 1
  190. end
  191. -- Highlight comments
  192. local comment_pos = string.find(line_text, "--", 1, true)
  193. if comment_pos then
  194. local range = lumacs.Range(
  195. lumacs.Position(line_num, comment_pos - 1),
  196. lumacs.Position(line_num, #line_text)
  197. )
  198. buf:set_style(range, lumacs.TextAttribute(lumacs.ColorType.Comment, 0))
  199. end
  200. end
  201. end,
  202. setup = function()
  203. print("[lua-mode] Lua mode activated")
  204. end,
  205. cleanup = function()
  206. print("[lua-mode] Lua mode deactivated")
  207. end,
  208. keybindings = {
  209. -- Lua-specific keybindings can go here
  210. }
  211. })
  212. -- Fundamental Mode (default/fallback)
  213. define_major_mode("fundamental-mode", {
  214. file_patterns = {},
  215. setup = function()
  216. print("[fundamental-mode] Fundamental mode activated")
  217. end
  218. })
  219. -- ============================================================================
  220. -- MINOR MODES
  221. -- ============================================================================
  222. -- Auto-save minor mode
  223. define_minor_mode("auto-save-mode", {
  224. global = false,
  225. setup = function()
  226. -- TODO: Set up auto-save timer
  227. print("[auto-save-mode] Auto-save enabled")
  228. end,
  229. cleanup = function()
  230. print("[auto-save-mode] Auto-save disabled")
  231. end
  232. })
  233. -- Line numbers minor mode (conceptual - already always shown)
  234. define_minor_mode("line-numbers-mode", {
  235. global = true,
  236. setup = function()
  237. print("[line-numbers-mode] Line numbers enabled")
  238. end,
  239. cleanup = function()
  240. print("[line-numbers-mode] Line numbers disabled")
  241. end
  242. })
  243. -- ============================================================================
  244. -- GLOBAL KEYBINDINGS
  245. -- ============================================================================
  246. -- Example: Custom keybindings
  247. -- Syntax: bind_key("key", function() ... end)
  248. -- Emacs-style navigation (Ctrl+N/P for next/previous line)
  249. bind_key("C-n", function()
  250. editor:move_down()
  251. message("Moved down")
  252. end)
  253. bind_key("C-p", function()
  254. editor:move_up()
  255. message("Moved up")
  256. end)
  257. bind_key("C-f", function()
  258. editor:move_right()
  259. end)
  260. bind_key("C-b", function()
  261. editor:move_left()
  262. end)
  263. -- Emacs-style line navigation
  264. bind_key("C-a", function()
  265. editor:move_to_line_start()
  266. end)
  267. bind_key("C-e", function()
  268. editor:move_to_line_end()
  269. end)
  270. -- M-f (forward-word) - Move forward one word
  271. bind_key("M-f", function()
  272. editor:move_forward_word()
  273. end)
  274. -- M-b (backward-word) - Move backward one word
  275. bind_key("M-b", function()
  276. editor:move_backward_word()
  277. end)
  278. -- C-v (scroll-up) - Page down
  279. bind_key("C-v", function()
  280. editor:page_down()
  281. end)
  282. -- M-v (scroll-down) - Page up
  283. bind_key("M-v", function()
  284. editor:page_up()
  285. end)
  286. -- M-< (beginning-of-buffer) - Go to start
  287. bind_key("M-<", function()
  288. editor:goto_beginning()
  289. message("Beginning of buffer")
  290. end)
  291. -- M-> (end-of-buffer) - Go to end
  292. bind_key("M->", function()
  293. editor:goto_end()
  294. message("End of buffer")
  295. end)
  296. -- M-g M-g (goto-line) - Jump to line number
  297. bind_key("M-g g", function()
  298. editor:command_mode()
  299. -- TODO: Implement line number input in command mode
  300. end)
  301. -- Custom command: Save buffer
  302. bind_key("C-s", function()
  303. local buf = editor.buffer
  304. if buf:save() then
  305. message("Buffer saved: " .. buf:name())
  306. else
  307. message("Failed to save buffer")
  308. end
  309. end)
  310. -- Custom command: Insert timestamp
  311. bind_key("C-t", function()
  312. local cursor_pos = editor.cursor
  313. local timestamp = os.date("%Y-%m-%d %H:%M:%S")
  314. editor.buffer:insert(cursor_pos, timestamp)
  315. message("Inserted timestamp")
  316. end)
  317. -- Example: Helper functions you can define
  318. function goto_line(line_num)
  319. local pos = lumacs.Position(line_num - 1, 0)
  320. editor:set_cursor(pos)
  321. message("Jumped to line " .. line_num)
  322. end
  323. -- Example: Buffer inspection
  324. function buffer_info()
  325. local buf = editor.buffer
  326. local cursor = editor.cursor
  327. message(string.format(
  328. "Buffer: %s | Lines: %d | Cursor: %d,%d | Modified: %s",
  329. buf:name(),
  330. buf:line_count(),
  331. cursor.line + 1,
  332. cursor.column + 1,
  333. buf:is_modified() and "yes" or "no"
  334. ))
  335. end
  336. -- Bind to show buffer info
  337. -- Note: C-i and Tab are indistinguishable in most terminals (both send ASCII 9)
  338. -- Using C-u instead for buffer info
  339. bind_key("C-u", buffer_info)
  340. -- Search helper function
  341. function find_next(query)
  342. local buf = editor.buffer
  343. local cursor = editor.cursor
  344. -- Start searching AFTER the current cursor position to find the next occurrence
  345. -- Otherwise we might find the same one if we are sitting on it.
  346. -- A simple way is to advance column by 1 for the search start.
  347. local search_start = lumacs.Position(cursor.line, cursor.column + 1)
  348. -- If at end of line, search from start of next line is handled by find() implementation?
  349. -- Buffer::find currently implements simple linear search from a position.
  350. -- If column is beyond end, it should handle it. Let's trust the C++ impl or adjust.
  351. local res = buf:find(query, search_start)
  352. if res then
  353. editor.cursor = res.start
  354. message("Found '" .. query .. "' at " .. res.start.line .. ":" .. res.start.column)
  355. -- Optional: Highlight the found range?
  356. else
  357. message("'" .. query .. "' not found")
  358. end
  359. end
  360. -- Example binding: Find "TODO"
  361. bind_key("C-o", function() find_next("TODO") end)
  362. -- Line swapping functions (like Emacs M-up/down or VS Code Alt+arrows)
  363. function swap_line_up()
  364. local buf = editor.buffer
  365. local cursor = editor.cursor
  366. -- Can't move first line up
  367. if cursor.line == 0 then
  368. message("Already at first line")
  369. return
  370. end
  371. message("DEBUG: Starting swap_line_up, cursor at line " .. cursor.line)
  372. -- Get the current line and above line text
  373. local current_line = buf:line(cursor.line)
  374. local above_line = buf:line(cursor.line - 1)
  375. -- Strategy: Replace both lines with them swapped
  376. -- Delete from start of line above to end of current line (not including next line)
  377. local delete_start = lumacs.Position(cursor.line - 1, 0)
  378. local delete_end = lumacs.Position(cursor.line, string.len(current_line))
  379. local range = lumacs.Range(delete_start, delete_end)
  380. buf:erase(range)
  381. -- Insert them back in swapped order
  382. -- Add extra newline if above_line is empty to preserve it
  383. local insert_pos = lumacs.Position(cursor.line - 1, 0)
  384. local text = current_line .. "\n" .. above_line
  385. if above_line == "" then
  386. text = text .. "\n"
  387. end
  388. buf:insert(insert_pos, text)
  389. -- Move cursor up to follow the line
  390. editor.cursor = lumacs.Position(cursor.line - 1, cursor.column)
  391. message("Swapped line up")
  392. end
  393. function swap_line_down()
  394. local buf = editor.buffer
  395. local cursor = editor.cursor
  396. -- Can't move last line down
  397. if cursor.line >= buf:line_count() - 1 then
  398. message("Already at last line")
  399. return
  400. end
  401. -- Get the current line and the line below
  402. local current_line = buf:line(cursor.line)
  403. local below_line = buf:line(cursor.line + 1)
  404. -- Strategy: Replace both lines with them swapped
  405. -- Delete from start of current line to end of line below (not including line after)
  406. local delete_start = lumacs.Position(cursor.line, 0)
  407. local delete_end = lumacs.Position(cursor.line + 1, string.len(below_line))
  408. local range = lumacs.Range(delete_start, delete_end)
  409. buf:erase(range)
  410. -- Insert them back in swapped order
  411. -- Add extra newline if current_line is empty to preserve it
  412. local insert_pos = lumacs.Position(cursor.line, 0)
  413. local text = below_line .. "\n" .. current_line
  414. if current_line == "" then
  415. text = text .. "\n"
  416. end
  417. buf:insert(insert_pos, text)
  418. -- Move cursor down to follow the line
  419. editor.cursor = lumacs.Position(cursor.line + 1, cursor.column)
  420. message("Swapped line down")
  421. end
  422. -- Bind to M-ArrowUp and M-ArrowDown (Meta/Alt + arrows)
  423. bind_key("M-ArrowUp", swap_line_up)
  424. bind_key("M-ArrowDown", swap_line_down)
  425. -- ============================================================================
  426. -- WINDOW MANAGEMENT
  427. -- ============================================================================
  428. -- Split horizontal (like Emacs C-x 2, simplified to M-2)
  429. bind_key("M-2", function()
  430. editor:split_horizontally()
  431. message("Split horizontally")
  432. end)
  433. -- Split vertical (like Emacs C-x 3, simplified to M-3)
  434. bind_key("M-3", function()
  435. editor:split_vertically()
  436. message("Split vertically")
  437. end)
  438. -- Close window (like Emacs C-x 0, simplified to M-0)
  439. bind_key("M-0", function()
  440. editor:close_window()
  441. message("Closed window")
  442. end)
  443. -- Command Mode (Minibuffer)
  444. bind_key("M-x", function()
  445. editor:command_mode()
  446. end)
  447. -- ============================================================================
  448. -- MARK AND REGION (Emacs-style selection)
  449. -- ============================================================================
  450. -- C-@ or C-SPC (set-mark-command) - Set the mark at cursor
  451. bind_key("C-@", function()
  452. local buf = editor.buffer
  453. local cursor = editor.cursor
  454. buf:set_mark(cursor)
  455. message("Mark set")
  456. end)
  457. -- For terminals that don't support C-@, also bind to C-SPC (but C-SPC is hard to detect)
  458. -- Most terminals send C-@ for C-SPC, so the above should work
  459. -- C-x C-x (exchange-point-and-mark) - Swap cursor and mark
  460. bind_key("C-x C-x", function()
  461. local buf = editor.buffer
  462. local mark = buf:mark()
  463. if not mark then
  464. message("No mark set")
  465. return
  466. end
  467. local cursor = editor.cursor
  468. buf:set_mark(cursor) -- Set mark at old cursor position
  469. editor.cursor = mark -- Move cursor to old mark position
  470. message("Mark and point exchanged")
  471. end)
  472. -- C-x h (mark-whole-buffer) - Select entire buffer
  473. bind_key("C-x h", function()
  474. local buf = editor.buffer
  475. -- Set mark at beginning
  476. buf:set_mark(lumacs.Position(0, 0))
  477. -- Move cursor to end
  478. local last_line = buf:line_count() - 1
  479. local last_col = #buf:line(last_line)
  480. editor.cursor = lumacs.Position(last_line, last_col)
  481. message("Buffer marked")
  482. end)
  483. -- ============================================================================
  484. -- KILL RING (Emacs cut/copy/paste)
  485. -- ============================================================================
  486. -- C-w (kill-region) - Cut selection
  487. bind_key("C-w", function()
  488. editor:kill_region()
  489. end)
  490. -- M-w (kill-ring-save) - Copy selection
  491. bind_key("M-w", function()
  492. editor:copy_region_as_kill()
  493. end)
  494. -- C-k (kill-line) - Cut from cursor to end of line
  495. bind_key("C-k", function()
  496. editor:kill_line()
  497. end)
  498. -- C-y (yank) - Paste
  499. bind_key("C-y", function()
  500. editor:yank()
  501. end)
  502. -- M-y (yank-pop) - Cycle through kill ring after yanking
  503. bind_key("M-y", function()
  504. editor:yank_pop()
  505. end)
  506. -- ============================================================================
  507. -- UNDO/REDO
  508. -- ============================================================================
  509. -- C-/ or C-_ for undo (traditional Emacs binding)
  510. bind_key("C-/", function()
  511. if editor:undo() then
  512. message("Undid change")
  513. else
  514. message("Nothing to undo")
  515. end
  516. end)
  517. -- Also keep C-z for undo (common in other editors)
  518. bind_key("C-z", function()
  519. if editor:undo() then
  520. message("Undid change")
  521. else
  522. message("Nothing to undo")
  523. end
  524. end)
  525. -- C-x u for redo (less common but sometimes used)
  526. bind_key("C-x u", function()
  527. if editor:redo() then
  528. message("Redid change")
  529. else
  530. message("Nothing to redo")
  531. end
  532. end)
  533. -- Manual re-highlight key (re-applies current major mode's highlighting)
  534. bind_key("C-l", function()
  535. local mode_name = current_major_mode()
  536. local mode = major_modes[mode_name]
  537. if mode and mode.highlight then
  538. mode.highlight()
  539. -- Debug: Count applied styles
  540. local buf = editor.buffer
  541. local styles_count = 0
  542. for line = 0, buf:line_count() - 1 do
  543. local styles = buf:get_line_styles(line)
  544. styles_count = styles_count + #styles
  545. end
  546. message(string.format("Re-highlighted with %s (%d styles)", mode_name, styles_count))
  547. else
  548. message("Current mode has no highlighting: " .. mode_name)
  549. end
  550. end)
  551. -- Mode information and control
  552. bind_key("C-h m", function()
  553. local mode_name = current_major_mode()
  554. local buf = editor.buffer
  555. local buf_name = buf:name()
  556. -- Get active minor modes
  557. local minor_list = {}
  558. if buffer_minor_modes[buf_name] then
  559. for mode, _ in pairs(buffer_minor_modes[buf_name]) do
  560. table.insert(minor_list, mode)
  561. end
  562. end
  563. local minor_str = #minor_list > 0 and table.concat(minor_list, ", ") or "none"
  564. message(string.format("Major: %s | Minor: %s", mode_name, minor_str))
  565. end)
  566. -- Test Escape key binding
  567. bind_key("Escape", function()
  568. message("Escape pressed! (Direct binding works)")
  569. end)
  570. -- C-x sequence bindings (Emacs style)
  571. bind_key("C-x o", function()
  572. editor:next_window()
  573. message("Switched window with C-x o")
  574. end)
  575. bind_key("C-x 2", function()
  576. editor:split_horizontally()
  577. message("Split horizontally with C-x 2")
  578. end)
  579. bind_key("C-x 3", function()
  580. editor:split_vertically()
  581. message("Split vertically with C-x 3")
  582. end)
  583. bind_key("C-x 0", function()
  584. editor:close_window()
  585. message("Closed window with C-x 0")
  586. end)
  587. -- Test control keys (ncurses versions)
  588. bind_key("C-k", function()
  589. message("C-k pressed! (Control key working with ncurses)")
  590. end)
  591. bind_key("C-s", function()
  592. local buf = editor.buffer
  593. if buf:save() then
  594. message("Buffer saved with C-s (ncurses)!")
  595. else
  596. message("Failed to save buffer")
  597. end
  598. end)
  599. -- Welcome message
  600. message("Lumacs ready! C-k=kill, C-y=yank, C-@=mark, C-w=cut, M-w=copy, M-f/b=word, C-v/M-v=page")
  601. -- Auto-activate mode for initial buffer
  602. auto_activate_major_mode()