init.lua 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  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. -- M-d (kill-word) - Kill word forward
  507. bind_key("M-d", function()
  508. editor:kill_word()
  509. end)
  510. -- M-Backspace (backward-kill-word) - Kill word backward
  511. bind_key("M-Backspace", function()
  512. editor:backward_kill_word()
  513. end)
  514. -- ============================================================================
  515. -- UNDO/REDO
  516. -- ============================================================================
  517. -- C-/ or C-_ for undo (traditional Emacs binding)
  518. bind_key("C-/", function()
  519. if editor:undo() then
  520. message("Undid change")
  521. else
  522. message("Nothing to undo")
  523. end
  524. end)
  525. -- Also keep C-z for undo (common in other editors)
  526. bind_key("C-z", function()
  527. if editor:undo() then
  528. message("Undid change")
  529. else
  530. message("Nothing to undo")
  531. end
  532. end)
  533. -- C-x u for redo (less common but sometimes used)
  534. bind_key("C-x u", function()
  535. if editor:redo() then
  536. message("Redid change")
  537. else
  538. message("Nothing to redo")
  539. end
  540. end)
  541. -- Manual re-highlight key (re-applies current major mode's highlighting)
  542. bind_key("C-l", function()
  543. local mode_name = current_major_mode()
  544. local mode = major_modes[mode_name]
  545. if mode and mode.highlight then
  546. mode.highlight()
  547. -- Debug: Count applied styles
  548. local buf = editor.buffer
  549. local styles_count = 0
  550. for line = 0, buf:line_count() - 1 do
  551. local styles = buf:get_line_styles(line)
  552. styles_count = styles_count + #styles
  553. end
  554. message(string.format("Re-highlighted with %s (%d styles)", mode_name, styles_count))
  555. else
  556. message("Current mode has no highlighting: " .. mode_name)
  557. end
  558. end)
  559. -- Mode information and control
  560. bind_key("C-h m", function()
  561. local mode_name = current_major_mode()
  562. local buf = editor.buffer
  563. local buf_name = buf:name()
  564. -- Get active minor modes
  565. local minor_list = {}
  566. if buffer_minor_modes[buf_name] then
  567. for mode, _ in pairs(buffer_minor_modes[buf_name]) do
  568. table.insert(minor_list, mode)
  569. end
  570. end
  571. local minor_str = #minor_list > 0 and table.concat(minor_list, ", ") or "none"
  572. message(string.format("Major: %s | Minor: %s", mode_name, minor_str))
  573. end)
  574. -- Test Escape key binding
  575. bind_key("Escape", function()
  576. message("Escape pressed! (Direct binding works)")
  577. end)
  578. -- C-x sequence bindings (Emacs style)
  579. bind_key("C-x o", function()
  580. editor:next_window()
  581. message("Switched window with C-x o")
  582. end)
  583. bind_key("C-x 2", function()
  584. editor:split_horizontally()
  585. message("Split horizontally with C-x 2")
  586. end)
  587. bind_key("C-x 3", function()
  588. editor:split_vertically()
  589. message("Split vertically with C-x 3")
  590. end)
  591. bind_key("C-x 0", function()
  592. editor:close_window()
  593. message("Closed window with C-x 0")
  594. end)
  595. -- ============================================================================
  596. -- BUFFER MANAGEMENT (C-x b, C-x C-b, C-x k)
  597. -- ============================================================================
  598. -- C-x b: Switch to buffer (with tab completion)
  599. bind_key("C-x b", function()
  600. editor:buffer_switch_mode()
  601. end)
  602. -- C-x k: Kill buffer (with tab completion)
  603. bind_key("C-x k", function()
  604. editor:kill_buffer_mode()
  605. end)
  606. -- C-x C-b: List all buffers
  607. bind_key("C-x C-b", function()
  608. local buffer_info = editor:get_all_buffer_info()
  609. if #buffer_info == 0 then
  610. message("No buffers open")
  611. return
  612. end
  613. -- Format buffer list
  614. local lines = {}
  615. table.insert(lines, "Buffer List:")
  616. table.insert(lines, "------------")
  617. table.insert(lines, "")
  618. table.insert(lines, string.format("%-3s %-20s %-10s %s", "Mod", "Name", "Size", "File"))
  619. table.insert(lines, string.format("%-3s %-20s %-10s %s", "---", "----", "----", "----"))
  620. for i, info in ipairs(buffer_info) do
  621. local modified = info.modified and " * " or " "
  622. local filepath = ""
  623. if info.filepath then
  624. filepath = tostring(info.filepath)
  625. end
  626. local line = string.format("%s %-20s %-10d %s",
  627. modified,
  628. info.name,
  629. info.size,
  630. filepath
  631. )
  632. table.insert(lines, line)
  633. end
  634. local list_text = table.concat(lines, "\n")
  635. local list_buf_name = "*Buffer List*"
  636. -- Switch to or create buffer
  637. local list_buf = editor:get_buffer_by_name(list_buf_name)
  638. if list_buf then
  639. editor:switch_buffer_in_window(list_buf_name)
  640. else
  641. editor:new_buffer(list_buf_name)
  642. end
  643. local buf = editor.buffer
  644. buf:clear()
  645. buf:insert(lumacs.Position(0,0), list_text)
  646. editor:goto_beginning()
  647. message(string.format("Buffer list (%d buffers)", #buffer_info))
  648. end)
  649. -- ============================================================================
  650. -- CASE CONVERSION (M-u, M-l, M-c)
  651. -- ============================================================================
  652. -- M-u (upcase-word)
  653. bind_key("M-u", function()
  654. local start_pos = editor.cursor
  655. editor:move_forward_word()
  656. local end_pos = editor.cursor
  657. local range = lumacs.Range(start_pos, end_pos)
  658. local text = editor.buffer:get_text_in_range(range)
  659. if #text > 0 then
  660. editor.buffer:replace(range, string.upper(text))
  661. end
  662. end)
  663. -- M-l (downcase-word)
  664. bind_key("M-l", function()
  665. local start_pos = editor.cursor
  666. editor:move_forward_word()
  667. local end_pos = editor.cursor
  668. local range = lumacs.Range(start_pos, end_pos)
  669. local text = editor.buffer:get_text_in_range(range)
  670. if #text > 0 then
  671. editor.buffer:replace(range, string.lower(text))
  672. end
  673. end)
  674. -- M-c (capitalize-word)
  675. bind_key("M-c", function()
  676. local start_pos = editor.cursor
  677. editor:move_forward_word()
  678. local end_pos = editor.cursor
  679. local range = lumacs.Range(start_pos, end_pos)
  680. local text = editor.buffer:get_text_in_range(range)
  681. if #text > 0 then
  682. local cap_text = text:sub(1,1):upper() .. text:sub(2):lower()
  683. editor.buffer:replace(range, cap_text)
  684. end
  685. end)
  686. -- C-x C-u (upcase-region)
  687. bind_key("C-x C-u", function()
  688. local range = editor.buffer:get_region(editor.cursor)
  689. if not range then
  690. message("No active region")
  691. return
  692. end
  693. local text = editor.buffer:get_text_in_range(range)
  694. if #text > 0 then
  695. editor.buffer:replace(range, string.upper(text))
  696. editor.buffer:deactivate_mark()
  697. end
  698. end)
  699. -- C-x C-l (downcase-region)
  700. bind_key("C-x C-l", function()
  701. local range = editor.buffer:get_region(editor.cursor)
  702. if not range then
  703. message("No active region")
  704. return
  705. end
  706. local text = editor.buffer:get_text_in_range(range)
  707. if #text > 0 then
  708. editor.buffer:replace(range, string.lower(text))
  709. editor.buffer:deactivate_mark()
  710. end
  711. end)
  712. -- ============================================================================
  713. -- COMMENTING (M-;)
  714. -- ============================================================================
  715. function escape_pattern(text)
  716. return text:gsub("([^%w])", "%%%1")
  717. end
  718. function comment_dwim()
  719. local mode_name = current_major_mode()
  720. local mode = major_modes[mode_name]
  721. local prefix = mode and mode.comment_syntax or "--"
  722. local escaped_prefix = escape_pattern(prefix)
  723. local range = editor.buffer:get_region(editor.cursor)
  724. if range then
  725. -- Region handling
  726. local start_line = range.start.line
  727. local end_line = range["end"].line
  728. -- Check if all lines are commented
  729. local all_commented = true
  730. for i = start_line, end_line do
  731. local line = editor.buffer:line(i)
  732. -- Ignore empty lines for decision
  733. if #line > 0 and not string.match(line, "^%s*" .. escaped_prefix) then
  734. all_commented = false
  735. break
  736. end
  737. end
  738. -- Apply change
  739. for i = start_line, end_line do
  740. local line = editor.buffer:line(i)
  741. local line_range = lumacs.Range(lumacs.Position(i, 0), lumacs.Position(i, #line))
  742. if #line > 0 then
  743. if all_commented then
  744. -- Uncomment
  745. local s, e = string.find(line, escaped_prefix)
  746. if s then
  747. local suffix = line:sub(e+1)
  748. if suffix:sub(1,1) == " " then suffix = suffix:sub(2) end
  749. local new_line = line:sub(1, s-1) .. suffix
  750. editor.buffer:replace(line_range, new_line)
  751. end
  752. else
  753. -- Comment (if not already commented)
  754. if not string.match(line, "^%s*" .. escaped_prefix) then
  755. local indent = string.match(line, "^%s*")
  756. local content = line:sub(#indent + 1)
  757. local new_line = indent .. prefix .. " " .. content
  758. editor.buffer:replace(line_range, new_line)
  759. end
  760. end
  761. end
  762. end
  763. else
  764. -- Single line
  765. local line_num = editor.cursor.line
  766. local line = editor.buffer:line(line_num)
  767. local line_range = lumacs.Range(lumacs.Position(line_num, 0), lumacs.Position(line_num, #line))
  768. if string.match(line, "^%s*" .. escaped_prefix) then
  769. -- Uncomment
  770. local s, e = string.find(line, escaped_prefix)
  771. if s then
  772. local suffix = line:sub(e+1)
  773. if suffix:sub(1,1) == " " then suffix = suffix:sub(2) end
  774. local new_line = line:sub(1, s-1) .. suffix
  775. editor.buffer:replace(line_range, new_line)
  776. end
  777. else
  778. -- Comment
  779. local indent = string.match(line, "^%s*")
  780. local content = line:sub(#indent + 1)
  781. local new_line = indent .. prefix .. " " .. content
  782. editor.buffer:replace(line_range, new_line)
  783. end
  784. end
  785. end
  786. bind_key("M-;", comment_dwim)
  787. -- ============================================================================
  788. -- REGISTERS (C-x r s, C-x r i)
  789. -- ============================================================================
  790. -- Helper function to prompt for register character
  791. function get_register_char(prompt_msg)
  792. message(prompt_msg)
  793. -- For now we'll use a simple approach - this would need UI integration
  794. -- In a full implementation, this would wait for a single character input
  795. -- For demo purposes, we'll use 'a' as default
  796. return 'a'
  797. end
  798. -- C-x r s (copy-to-register) - Save region to register
  799. bind_key("C-x r s", function()
  800. local register_char = get_register_char("Save to register:")
  801. editor:copy_region_to_register(register_char)
  802. end)
  803. -- C-x r i (insert-register) - Insert from register
  804. bind_key("C-x r i", function()
  805. local register_char = get_register_char("Insert register:")
  806. editor:yank_from_register(register_char)
  807. end)
  808. -- ============================================================================
  809. -- RECTANGLES (C-x r k/y/t)
  810. -- ============================================================================
  811. -- C-x r k (kill-rectangle) - Cut rectangular region
  812. bind_key("C-x r k", function()
  813. editor:kill_rectangle()
  814. end)
  815. -- C-x r y (yank-rectangle) - Paste rectangular region
  816. bind_key("C-x r y", function()
  817. editor:yank_rectangle()
  818. end)
  819. -- C-x r t (string-rectangle) - Fill rectangle with text
  820. bind_key("C-x r t", function()
  821. -- For demo purposes, we'll fill with asterisks
  822. -- In a full implementation, this would prompt for text input
  823. editor:string_rectangle("*")
  824. message("Rectangle filled with '*' - C-x r t demo")
  825. end)
  826. -- ============================================================================
  827. -- KEYBOARD MACROS (F3, F4)
  828. -- ============================================================================
  829. -- F3 - start-kbd-macro
  830. bind_key("F3", function()
  831. editor:start_kbd_macro()
  832. end)
  833. -- F4 - end-kbd-macro or call-last-kbd-macro
  834. bind_key("F4", function()
  835. editor:end_kbd_macro_or_call()
  836. end)
  837. -- ============================================================================
  838. -- INCREMENTAL SEARCH (C-s, C-r)
  839. -- ============================================================================
  840. -- C-s (isearch-forward)
  841. bind_key("C-s", function()
  842. editor:isearch_mode()
  843. end)
  844. -- C-r (isearch-backward)
  845. bind_key("C-r", function()
  846. editor:isearch_backward_mode()
  847. end)
  848. -- Test control keys (ncurses versions)
  849. bind_key("C-k", function()
  850. message("C-k pressed! (Control key working with ncurses)")
  851. end)
  852. bind_key("C-s", function()
  853. local buf = editor.buffer
  854. if buf:save() then
  855. message("Buffer saved with C-s (ncurses)!")
  856. else
  857. message("Failed to save buffer")
  858. end
  859. end)
  860. -- ============================================================================
  861. -- CONFIGURATION FUNCTIONS
  862. -- ============================================================================
  863. -- Toggle line numbers on/off
  864. function toggle_line_numbers()
  865. local config = editor.config
  866. local current = config:get_bool("show_line_numbers", true)
  867. config:set("show_line_numbers", not current)
  868. if not current then
  869. message("Line numbers enabled")
  870. else
  871. message("Line numbers disabled")
  872. end
  873. end
  874. -- Set line number width
  875. function set_line_number_width(width)
  876. editor.config:set("line_number_width", width)
  877. message("Line number width set to " .. width)
  878. end
  879. -- Show current configuration
  880. function show_config()
  881. local config = editor.config
  882. local show_nums = config:get_bool("show_line_numbers", true)
  883. local width = config:get_int("line_number_width", 6)
  884. message(string.format("Line numbers: %s, Width: %d", show_nums and "on" or "off", width))
  885. end
  886. -- Toggle modeline (status bar for each window) function
  887. function toggle_modeline()
  888. local current = editor.config:get_bool("show_modeline", true)
  889. editor.config:set_bool("show_modeline", not current)
  890. if current then
  891. message("Modeline disabled")
  892. else
  893. message("Modeline enabled")
  894. end
  895. end
  896. -- Bind configuration functions
  897. bind_key("C-x l", toggle_line_numbers) -- C-x l to toggle line numbers
  898. bind_key("C-x m", toggle_modeline) -- C-x m to toggle modeline
  899. bind_key("C-x C-c", show_config) -- C-x C-c to show config
  900. -- Load theme configuration
  901. dofile("themes.lua")
  902. -- Welcome message
  903. 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")
  904. -- Auto-activate mode for initial buffer
  905. auto_activate_major_mode()
  906. -- ============================================================================
  907. -- COMMAND REGISTRY (M-x support)
  908. -- ============================================================================
  909. lumacs.command_registry = {}
  910. function define_command(name, func, doc)
  911. lumacs.command_registry[name] = {
  912. func = func,
  913. doc = doc or "No documentation"
  914. }
  915. end
  916. function execute_extended_command(name)
  917. local cmd = lumacs.command_registry[name]
  918. if cmd then
  919. cmd.func()
  920. return true
  921. end
  922. return false
  923. end
  924. function get_command_names()
  925. local names = {}
  926. for name, _ in pairs(lumacs.command_registry) do
  927. table.insert(names, name)
  928. end
  929. table.sort(names)
  930. return names
  931. end
  932. -- File and Buffer Commands
  933. define_command("save-buffer", function()
  934. if editor.buffer:save() then
  935. message("Saved " .. editor.buffer:name())
  936. else
  937. message("Save failed")
  938. end
  939. end, "Save current buffer")
  940. define_command("find-file", function()
  941. editor:find_file_mode()
  942. end, "Find file")
  943. define_command("kill-buffer", function()
  944. editor:kill_buffer_mode()
  945. end, "Kill buffer")
  946. define_command("switch-buffer", function()
  947. editor:buffer_switch_mode()
  948. end, "Switch buffer")
  949. define_command("list-buffers", function()
  950. -- Use existing implementation via keybinding or duplicate logic?
  951. -- Calling the function bound to C-x C-b if we can find it, or just define it here.
  952. -- Since C-x C-b binding is anonymous function, I'll copy logic or better,
  953. -- extract list-buffers logic in init.lua (future refactor).
  954. -- For now, I'll just invoke the binding C-x C-b if possible? No.
  955. -- I'll just leave it for now or copy-paste the logic.
  956. -- Copying logic is safer for now.
  957. local buffer_info = editor:get_all_buffer_info()
  958. if #buffer_info == 0 then
  959. message("No buffers open")
  960. return
  961. end
  962. local lines = {}
  963. table.insert(lines, "Buffer List:")
  964. table.insert(lines, "------------")
  965. table.insert(lines, "")
  966. table.insert(lines, string.format("%-3s %-20s %-10s %s", "Mod", "Name", "Size", "File"))
  967. table.insert(lines, string.format("%-3s %-20s %-10s %s", "---", "----", "----", "----"))
  968. for i, info in ipairs(buffer_info) do
  969. local modified = info.modified and " * " or " "
  970. local filepath = ""
  971. if info.filepath then filepath = tostring(info.filepath) end
  972. table.insert(lines, string.format("%s %-20s %-10d %s", modified, info.name, info.size, filepath))
  973. end
  974. local list_text = table.concat(lines, "\n")
  975. local list_buf_name = "*Buffer List*"
  976. local list_buf = editor:get_buffer_by_name(list_buf_name)
  977. if list_buf then
  978. editor:switch_buffer_in_window(list_buf_name)
  979. else
  980. editor:new_buffer(list_buf_name)
  981. end
  982. editor.buffer:clear()
  983. editor.buffer:insert(lumacs.Position(0,0), list_text)
  984. editor:goto_beginning()
  985. end, "List all buffers")
  986. -- Navigation
  987. define_command("next-line", function() editor:move_down() end, "Move cursor down")
  988. define_command("previous-line", function() editor:move_up() end, "Move cursor up")
  989. define_command("forward-char", function() editor:move_right() end, "Move cursor right")
  990. define_command("backward-char", function() editor:move_left() end, "Move cursor left")
  991. define_command("forward-word", function() editor:move_forward_word() end, "Move forward one word")
  992. define_command("backward-word", function() editor:move_backward_word() end, "Move backward one word")
  993. define_command("beginning-of-buffer", function() editor:goto_beginning() end, "Go to beginning of buffer")
  994. define_command("end-of-buffer", function() editor:goto_end() end, "Go to end of buffer")
  995. define_command("scroll-up-command", function() editor:page_down() end, "Page down")
  996. define_command("scroll-down-command", function() editor:page_up() end, "Page up")
  997. -- Window Management
  998. define_command("split-window-below", function() editor:split_horizontally() end, "Split window horizontally")
  999. define_command("split-window-right", function() editor:split_vertically() end, "Split window vertically")
  1000. define_command("delete-window", function() editor:close_window() end, "Close current window")
  1001. define_command("other-window", function() editor:next_window() end, "Select other window")
  1002. define_command("delete-other-windows", function()
  1003. -- Simplified: keep closing others until only 1?
  1004. -- Or just implement properly in C++ later.
  1005. -- For now, assume users use C-x 1 if implemented?
  1006. -- C-x 1 isn't implemented in init.lua yet.
  1007. message("delete-other-windows not implemented yet")
  1008. end, "Delete all other windows")
  1009. -- Editing
  1010. define_command("kill-line", function() editor:kill_line() end, "Kill rest of line")
  1011. define_command("kill-region", function() editor:kill_region() end, "Kill selected region")
  1012. define_command("copy-region-as-kill", function() editor:copy_region_as_kill() end, "Copy region")
  1013. define_command("yank", function() editor:yank() end, "Paste from kill ring")
  1014. define_command("undo", function() if editor:undo() then message("Undid") else message("No undo") end end, "Undo last change")
  1015. define_command("redo", function() if editor:redo() then message("Redid") else message("No redo") end end, "Redo last undo")
  1016. -- Modes
  1017. define_command("lua-mode", function() activate_major_mode("lua-mode") end, "Switch to Lua mode")
  1018. define_command("fundamental-mode", function() activate_major_mode("fundamental-mode") end, "Switch to Fundamental mode")
  1019. define_command("auto-save-mode", function() toggle_minor_mode("auto-save-mode") end, "Toggle auto-save")
  1020. message("Commands loaded. Try M-x list-buffers")