init.lua 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  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. editor:message("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. editor:message(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. editor:message(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. editor: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. editor:message(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. editor:message(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. editor:bind_key(key, func)
  70. end
  71. -- Run setup function
  72. mode.setup()
  73. editor: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. editor:message(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. editor: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. editor: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. editor: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. editor:message(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. editor:message("[lua-mode] Lua mode activated")
  204. end,
  205. cleanup = function()
  206. editor:message("[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. editor:message("[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. editor:message("[auto-save-mode] Auto-save enabled")
  228. end,
  229. cleanup = function()
  230. editor:message("[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. editor:message("[line-numbers-mode] Line numbers enabled")
  238. end,
  239. cleanup = function()
  240. editor:message("[line-numbers-mode] Line numbers disabled")
  241. end
  242. })
  243. -- ============================================================================
  244. -- GLOBAL KEYBINDINGS
  245. -- ============================================================================
  246. -- Example: Custom keybindings
  247. -- Syntax: editor:bind_key("key", function() ... end)
  248. -- Basic Editing Commands (moved from C++ fallback)
  249. function lumacs_insert_newline()
  250. local cursor = editor.cursor
  251. editor.buffer:insert_newline(cursor)
  252. editor:set_cursor(lumacs.Position(cursor.line + 1, 0))
  253. end
  254. editor:bind_key("Return", lumacs_insert_newline)
  255. editor:register_command("insert-newline", "Insert a new line at cursor position.", lumacs_insert_newline, true)
  256. function lumacs_backward_delete_char()
  257. local cursor = editor.cursor
  258. editor.buffer:erase_char(cursor)
  259. if cursor.column > 0 then
  260. editor:set_cursor(lumacs.Position(cursor.line, cursor.column - 1))
  261. elseif cursor.line > 0 then
  262. local prev_line_len = #editor.buffer:line(cursor.line - 1)
  263. editor:set_cursor(lumacs.Position(cursor.line - 1, prev_line_len))
  264. end
  265. end
  266. editor:bind_key("Backspace", lumacs_backward_delete_char)
  267. editor:register_command("backward-delete-char", "Delete the character before cursor.", lumacs_backward_delete_char, true)
  268. function lumacs_delete_char()
  269. local cursor = editor.cursor
  270. editor.buffer:erase_char(lumacs.Position(cursor.line, cursor.column + 1))
  271. end
  272. editor:bind_key("Delete", lumacs_delete_char)
  273. editor:register_command("delete-char", "Delete the character at cursor position.", lumacs_delete_char, true)
  274. -- Navigation Commands (explicitly bound arrow keys)
  275. editor:bind_key("ArrowUp", function() editor:move_up() end)
  276. editor:bind_key("ArrowDown", function() editor:move_down() end)
  277. editor:bind_key("ArrowLeft", function() editor:move_left() end)
  278. editor:bind_key("ArrowRight", function() editor:move_right() end)
  279. editor:bind_key("Home", function() editor:move_to_line_start() end)
  280. editor:bind_key("End", function() editor:move_to_line_end() end)
  281. -- Generic self-insert command for printable characters
  282. -- This command is special; it's called by the C++ core if no other binding matches a printable char.
  283. function self_insert_command(char_to_insert)
  284. local cursor = editor.cursor
  285. editor.buffer:insert(cursor, char_to_insert)
  286. editor:set_cursor(lumacs.Position(cursor.line, cursor.column + 1))
  287. -- Optionally, log for debugging
  288. -- local new_cursor = editor.cursor
  289. -- editor:message(string.format("[DEBUG Lua] Inserted '%s' at (%d,%d) -> cursor now at (%d,%d)",
  290. -- char_to_insert, cursor.line, cursor.column, new_cursor.line, new_cursor.column))
  291. end
  292. editor:register_command("self-insert-command", "Insert the character pressed.", self_insert_command, true)
  293. -- Emacs-style navigation (Ctrl+N/P for next/previous line)
  294. editor:bind_key("C-n", function()
  295. editor:move_down()
  296. editor:message("Moved down")
  297. end)
  298. editor:bind_key("C-p", function()
  299. editor:move_up()
  300. editor:message("Moved up")
  301. end)
  302. editor:bind_key("C-f", function()
  303. editor:move_right()
  304. end)
  305. editor:bind_key("C-b", function()
  306. editor:move_left()
  307. end)
  308. -- Emacs-style line navigation
  309. editor:bind_key("C-a", function()
  310. editor:move_to_line_start()
  311. end)
  312. editor:bind_key("C-e", function()
  313. editor:move_to_line_end()
  314. end)
  315. -- M-f (forward-word) - Move forward one word
  316. editor:bind_key("M-f", function()
  317. editor:move_forward_word()
  318. end)
  319. -- M-b (backward-word) - Move backward one word
  320. editor:bind_key("M-b", function()
  321. editor:move_backward_word()
  322. end)
  323. -- C-v (scroll-up) - Page down
  324. editor:bind_key("C-v", function()
  325. editor:page_down()
  326. end)
  327. -- M-v (scroll-down) - Page up
  328. editor:bind_key("M-v", function()
  329. editor:page_up()
  330. end)
  331. -- M-< (beginning-of-buffer) - Go to start
  332. editor:bind_key("M-<", function()
  333. editor:goto_beginning()
  334. editor:message("Beginning of buffer")
  335. end)
  336. -- M-> (end-of-buffer) - Go to end
  337. editor:bind_key("M->", function()
  338. editor:goto_end()
  339. editor:message("End of buffer")
  340. end)
  341. -- M-g M-g (goto-line) - Jump to line number
  342. editor:bind_key("M-g g", function()
  343. editor:command_mode()
  344. -- TODO: Implement line number input in command mode
  345. end)
  346. -- Note: C-s binding moved to avoid conflicts with isearch
  347. -- Custom command: Insert timestamp
  348. editor:bind_key("C-t", function()
  349. local cursor_pos = editor.cursor
  350. local timestamp = os.date("%Y-%m-%d %H:%M:%S")
  351. editor.buffer:insert(cursor_pos, timestamp)
  352. editor:message("Inserted timestamp")
  353. end)
  354. -- Example: Helper functions you can define
  355. function goto_line(line_num)
  356. local pos = lumacs.Position(line_num - 1, 0)
  357. editor:set_cursor(pos)
  358. editor:message("Jumped to line " .. line_num)
  359. end
  360. -- Example: Buffer inspection
  361. function buffer_info()
  362. local buf = editor.buffer
  363. local cursor = editor.cursor
  364. editor:message(string.format(
  365. "Buffer: %s | Lines: %d | Cursor: %d,%d | Modified: %s",
  366. buf:name(),
  367. buf:line_count(),
  368. cursor.line + 1,
  369. cursor.column + 1,
  370. buf:is_modified() and "yes" or "no"
  371. ))
  372. end
  373. -- Bind to show buffer info
  374. -- Note: C-i and Tab are indistinguishable in most terminals (both send ASCII 9)
  375. -- Using C-u instead for buffer info
  376. editor:bind_key("C-u", buffer_info)
  377. -- Search helper function
  378. function find_next(query)
  379. local buf = editor.buffer
  380. local cursor = editor.cursor
  381. -- Start searching AFTER the current cursor position to find the next occurrence
  382. -- Otherwise we might find the same one if we are sitting on it.
  383. -- A simple way is to advance column by 1 for the search start.
  384. local search_start = lumacs.Position(cursor.line, cursor.column + 1)
  385. -- If at end of line, search from start of next line is handled by find() implementation?
  386. -- Buffer::find currently implements simple linear search from a position.
  387. -- If column is beyond end, it should handle it. Let's trust the C++ impl or adjust.
  388. local res = buf:find(query, search_start)
  389. if res then
  390. editor.cursor = res.start
  391. editor:message("Found '" .. query .. "' at " .. res.start.line .. ":" .. res.start.column)
  392. -- Optional: Highlight the found range?
  393. else
  394. editor:message("'" .. query .. "' not found")
  395. end
  396. end
  397. -- Example binding: Find "TODO"
  398. editor:bind_key("C-o", function() find_next("TODO") end)
  399. -- Line swapping functions (like Emacs M-up/down or VS Code Alt+arrows)
  400. function swap_line_up()
  401. local buf = editor.buffer
  402. local cursor = editor.cursor
  403. -- Can't move first line up
  404. if cursor.line == 0 then
  405. editor:message("Already at first line")
  406. return
  407. end
  408. editor:message("DEBUG: Starting swap_line_up, cursor at line " .. cursor.line)
  409. -- Get the current line and above line text
  410. local current_line = buf:line(cursor.line)
  411. local above_line = buf:line(cursor.line - 1)
  412. -- Strategy: Replace both lines with them swapped
  413. -- Delete from start of line above to end of current line (not including next line)
  414. local delete_start = lumacs.Position(cursor.line - 1, 0)
  415. local delete_end = lumacs.Position(cursor.line, string.len(current_line))
  416. local range = lumacs.Range(delete_start, delete_end)
  417. buf:erase(range)
  418. -- Insert them back in swapped order
  419. -- Add extra newline if above_line is empty to preserve it
  420. local insert_pos = lumacs.Position(cursor.line - 1, 0)
  421. local text = current_line .. "\n" .. above_line
  422. if above_line == "" then
  423. text = text .. "\n"
  424. end
  425. buf:insert(insert_pos, text)
  426. -- Move cursor up to follow the line
  427. editor.cursor = lumacs.Position(cursor.line - 1, cursor.column)
  428. editor:message("Swapped line up")
  429. end
  430. function swap_line_down()
  431. local buf = editor.buffer
  432. local cursor = editor.cursor
  433. -- Can't move last line down
  434. if cursor.line >= buf:line_count() - 1 then
  435. editor:message("Already at last line")
  436. return
  437. end
  438. -- Get the current line and the line below
  439. local current_line = buf:line(cursor.line)
  440. local below_line = buf:line(cursor.line + 1)
  441. -- Strategy: Replace both lines with them swapped
  442. -- Delete from start of current line to end of line below (not including line after)
  443. local delete_start = lumacs.Position(cursor.line, 0)
  444. local delete_end = lumacs.Position(cursor.line + 1, string.len(below_line))
  445. local range = lumacs.Range(delete_start, delete_end)
  446. buf:erase(range)
  447. -- Insert them back in swapped order
  448. -- Add extra newline if current_line is empty to preserve it
  449. local insert_pos = lumacs.Position(cursor.line, 0)
  450. local text = below_line .. "\n" .. current_line
  451. if current_line == "" then
  452. text = text .. "\n"
  453. end
  454. buf:insert(insert_pos, text)
  455. -- Move cursor down to follow the line
  456. editor.cursor = lumacs.Position(cursor.line + 1, cursor.column)
  457. editor:message("Swapped line down")
  458. end
  459. -- Bind to M-ArrowUp and M-ArrowDown (Meta/Alt + arrows)
  460. editor:bind_key("M-ArrowUp", swap_line_up)
  461. editor:bind_key("M-ArrowDown", swap_line_down)
  462. -- ============================================================================
  463. -- WINDOW MANAGEMENT
  464. -- ============================================================================
  465. -- Split horizontal (like Emacs C-x 2, simplified to M-2)
  466. editor:bind_key("M-2", function()
  467. editor:split_horizontally()
  468. editor:message("Split horizontally")
  469. end)
  470. -- Split vertical (like Emacs C-x 3, simplified to M-3)
  471. editor:bind_key("M-3", function()
  472. editor:split_vertically()
  473. editor:message("Split vertically")
  474. end)
  475. -- Close window (like Emacs C-x 0, simplified to M-0)
  476. editor:bind_key("M-0", function()
  477. editor:close_window()
  478. editor:message("Closed window")
  479. end)
  480. -- Command Mode (Minibuffer)
  481. editor:bind_key("M-x", function()
  482. editor:command_mode()
  483. end)
  484. -- ============================================================================
  485. -- MARK AND REGION (Emacs-style selection)
  486. -- ============================================================================
  487. -- C-@ or C-SPC (set-mark-command) - Set the mark at cursor
  488. editor:bind_key("C-@", function()
  489. local buf = editor.buffer
  490. local cursor = editor.cursor
  491. buf:set_mark(cursor)
  492. editor:message("Mark set")
  493. end)
  494. -- For terminals that don't support C-@, also bind to C-SPC (but C-SPC is hard to detect)
  495. -- Most terminals send C-@ for C-SPC, so the above should work
  496. -- C-x C-x (exchange-point-and-mark) - Swap cursor and mark
  497. editor:bind_key("C-x C-x", function()
  498. local buf = editor.buffer
  499. local mark = buf.mark
  500. if not mark then
  501. editor:message("No mark set")
  502. return
  503. end
  504. local cursor = editor.cursor
  505. buf:set_mark(cursor) -- Set mark at old cursor position
  506. editor.cursor = mark -- Move cursor to old mark position
  507. editor:message("Mark and point exchanged")
  508. end)
  509. -- C-x h (mark-whole-buffer) - Select entire buffer
  510. editor:bind_key("C-x h", function()
  511. local buf = editor.buffer
  512. -- Set mark at beginning
  513. buf:set_mark(lumacs.Position(0, 0))
  514. -- Move cursor to end
  515. local last_line = buf:line_count() - 1
  516. local last_col = #buf:line(last_line)
  517. editor.cursor = lumacs.Position(last_line, last_col)
  518. editor:message("Buffer marked")
  519. end)
  520. -- ============================================================================
  521. -- KILL RING (Emacs cut/copy/paste)
  522. -- ============================================================================
  523. -- C-w (kill-region) - Cut selection
  524. editor:bind_key("C-w", function()
  525. editor:kill_region()
  526. end)
  527. -- M-w (kill-ring-save) - Copy selection
  528. editor:bind_key("M-w", function()
  529. editor:copy_region_as_kill()
  530. end)
  531. -- C-k (kill-line) - Cut from cursor to end of line
  532. editor:bind_key("C-k", function()
  533. editor:kill_line()
  534. editor:message("Killed line")
  535. end)
  536. -- C-y (yank) - Paste
  537. editor:bind_key("C-y", function()
  538. editor:yank()
  539. end)
  540. -- M-y (yank-pop) - Cycle through kill ring after yanking
  541. editor:bind_key("M-y", function()
  542. editor:yank_pop()
  543. end)
  544. -- M-d (kill-word) - Kill word forward
  545. editor:bind_key("M-d", function()
  546. editor:kill_word()
  547. end)
  548. -- M-Backspace (backward-kill-word) - Kill word backward
  549. editor:bind_key("M-Backspace", function()
  550. editor:backward_kill_word()
  551. end)
  552. -- ============================================================================
  553. -- UNDO/REDO
  554. -- ============================================================================
  555. -- C-/ or C-_ for undo (traditional Emacs binding)
  556. editor:bind_key("C-/", function()
  557. if editor:undo() then
  558. editor:message("Undid change")
  559. else
  560. editor:message("Nothing to undo")
  561. end
  562. end)
  563. -- Also keep C-z for undo (common in other editors)
  564. editor:bind_key("C-z", function()
  565. if editor:undo() then
  566. editor:message("Undid change")
  567. else
  568. editor:message("Nothing to undo")
  569. end
  570. end)
  571. -- C-x u for redo (less common but sometimes used)
  572. editor:bind_key("C-x u", function()
  573. if editor:redo() then
  574. editor:message("Redid change")
  575. else
  576. editor:message("Nothing to redo")
  577. end
  578. end)
  579. -- Manual re-highlight key (re-applies current major mode's highlighting)
  580. editor:bind_key("C-l", function()
  581. local mode_name = current_major_mode()
  582. local mode = major_modes[mode_name]
  583. if mode and mode.highlight then
  584. mode.highlight()
  585. -- Debug: Count applied styles
  586. local buf = editor.buffer
  587. local styles_count = 0
  588. for line = 0, buf:line_count() - 1 do
  589. local styles = buf:get_line_styles(line)
  590. styles_count = styles_count + #styles
  591. end
  592. editor:message(string.format("Re-highlighted with %s (%d styles)", mode_name, styles_count))
  593. else
  594. editor:message("Current mode has no highlighting: " .. mode_name)
  595. end
  596. end)
  597. -- Mode information and control
  598. editor:bind_key("C-h m", function()
  599. local mode_name = current_major_mode()
  600. local buf = editor.buffer
  601. local buf_name = buf:name()
  602. -- Get active minor modes
  603. local minor_list = {}
  604. if buffer_minor_modes[buf_name] then
  605. for mode, _ in pairs(buffer_minor_modes[buf_name]) do
  606. table.insert(minor_list, mode)
  607. end
  608. end
  609. local minor_str = #minor_list > 0 and table.concat(minor_list, ", ") or "none"
  610. editor:message(string.format("Major: %s | Minor: %s", mode_name, minor_str))
  611. end)
  612. -- Test Escape key binding
  613. editor:bind_key("Escape", function()
  614. editor:message("Escape pressed! (Direct binding works)")
  615. end)
  616. -- C-x sequence bindings (Emacs style)
  617. editor:bind_key("C-x o", function()
  618. editor:next_window()
  619. editor:message("Switched window with C-x o")
  620. end)
  621. editor:bind_key("C-x 2", function()
  622. editor:split_horizontally()
  623. editor:message("Split horizontally with C-x 2")
  624. end)
  625. editor:bind_key("C-x 3", function()
  626. editor:split_vertically()
  627. editor:message("Split vertically with C-x 3")
  628. end)
  629. editor:bind_key("C-x 0", function()
  630. editor:close_window()
  631. editor:message("Closed window with C-x 0")
  632. end)
  633. -- ============================================================================
  634. -- BUFFER MANAGEMENT (C-x b, C-x C-b, C-x k)
  635. -- ============================================================================
  636. -- C-x b: Switch to buffer (with tab completion)
  637. editor:bind_key("C-x b", function()
  638. editor:buffer_switch_mode()
  639. end)
  640. -- C-x k: Kill buffer (with tab completion)
  641. editor:bind_key("C-x k", function()
  642. editor:kill_buffer_mode()
  643. end)
  644. -- C-x C-b: List all buffers
  645. editor:bind_key("C-x C-b", function()
  646. local buffer_info = editor:get_all_buffer_info()
  647. if #buffer_info == 0 then
  648. editor:message("No buffers open")
  649. return
  650. end
  651. -- Format buffer list
  652. local lines = {}
  653. table.insert(lines, "Buffer List:")
  654. table.insert(lines, "------------")
  655. table.insert(lines, "")
  656. table.insert(lines, string.format("% -3s % -20s % -10s %s", "Mod", "Name", "Size", "File"))
  657. table.insert(lines, string.format("% -3s % -20s % -10s %s", "---", "----"))
  658. for i, info in ipairs(buffer_info) do
  659. local modified = info.modified and " * " or " "
  660. local filepath = ""
  661. if info.filepath then
  662. filepath = tostring(info.filepath)
  663. end
  664. local line = string.format("%s % -20s % -10d %s",
  665. modified,
  666. info.name,
  667. info.size,
  668. filepath
  669. )
  670. table.insert(lines, line)
  671. end
  672. local list_text = table.concat(lines, "\n")
  673. local list_buf_name = "*Buffer List*"
  674. -- Switch to or create buffer
  675. local list_buf = editor:get_buffer_by_name(list_buf_name)
  676. if list_buf then
  677. editor:switch_buffer_in_window(list_buf_name)
  678. else
  679. editor:new_buffer(list_buf_name)
  680. end
  681. local buf = editor.buffer
  682. buf:clear()
  683. buf:insert(lumacs.Position(0,0), list_text)
  684. editor:goto_beginning()
  685. editor:message(string.format("Buffer list (%d buffers)", #buffer_info))
  686. end)
  687. -- ============================================================================
  688. -- CASE CONVERSION (M-u, M-l, M-c)
  689. -- ============================================================================
  690. -- M-u (upcase-word)
  691. editor:bind_key("M-u", function()
  692. local start_pos = editor.cursor
  693. editor:move_forward_word()
  694. local end_pos = editor.cursor
  695. local range = lumacs.Range(start_pos, end_pos)
  696. local text = editor.buffer:get_text_in_range(range)
  697. if #text > 0 then
  698. editor.buffer:replace(range, string.upper(text))
  699. end
  700. end)
  701. -- M-l (downcase-word)
  702. editor:bind_key("M-l", function()
  703. local start_pos = editor.cursor
  704. editor:move_forward_word()
  705. local end_pos = editor.cursor
  706. local range = lumacs.Range(start_pos, end_pos)
  707. local text = editor.buffer:get_text_in_range(range)
  708. if #text > 0 then
  709. editor.buffer:replace(range, string.lower(text))
  710. end
  711. end)
  712. -- M-c (capitalize-word)
  713. editor:bind_key("M-c", function()
  714. local start_pos = editor.cursor
  715. editor:move_forward_word()
  716. local end_pos = editor.cursor
  717. local range = lumacs.Range(start_pos, end_pos)
  718. local text = editor.buffer:get_text_in_range(range)
  719. if #text > 0 then
  720. local cap_text = text:sub(1,1):upper() .. text:sub(2):lower()
  721. editor.buffer:replace(range, cap_text)
  722. end
  723. end)
  724. -- C-x C-u (upcase-region)
  725. editor:bind_key("C-x C-u", function()
  726. local range = editor.buffer:get_region(editor.cursor)
  727. if not range then
  728. editor:message("No active region")
  729. return
  730. end
  731. local text = editor.buffer:get_text_in_range(range)
  732. if #text > 0 then
  733. editor.buffer:replace(range, string.upper(text))
  734. editor.buffer:deactivate_mark()
  735. end
  736. end)
  737. -- C-x C-l (downcase-region)
  738. editor:bind_key("C-x C-l", function()
  739. local range = editor.buffer:get_region(editor.cursor)
  740. if not range then
  741. editor:message("No active region")
  742. return
  743. end
  744. local text = editor.buffer:get_text_in_range(range)
  745. if #text > 0 then
  746. editor.buffer:replace(range, string.lower(text))
  747. editor.buffer:deactivate_mark()
  748. end
  749. end)
  750. -- ============================================================================
  751. -- COMMENTING (M- ;)
  752. -- ============================================================================
  753. function escape_pattern(text)
  754. return text:gsub("([^%w])", "%%%1")
  755. end
  756. function comment_dwim()
  757. local mode_name = current_major_mode()
  758. local mode = major_modes[mode_name]
  759. local prefix = mode and mode.comment_syntax or "--"
  760. local escaped_prefix = escape_pattern(prefix)
  761. local range = editor.buffer:get_region(editor.cursor)
  762. if range then
  763. -- Region handling
  764. local start_line = range.start.line
  765. local end_line = range["end"].line
  766. -- Check if all lines are commented
  767. local all_commented = true
  768. for i = start_line, end_line do
  769. local line = editor.buffer:line(i)
  770. -- Ignore empty lines for decision
  771. if #line > 0 and not string.match(line, "^%s*" .. escaped_prefix) then
  772. all_commented = false
  773. break
  774. end
  775. end
  776. -- Apply change
  777. for i = start_line, end_line do
  778. local line = editor.buffer:line(i)
  779. local line_range = lumacs.Range(lumacs.Position(i, 0), lumacs.Position(i, #line))
  780. if #line > 0 then
  781. if all_commented then
  782. -- Uncomment
  783. local s, e = string.find(line, escaped_prefix)
  784. if s then
  785. local suffix = line:sub(e+1)
  786. if suffix:sub(1,1) == " " then suffix = suffix:sub(2) end
  787. local new_line = line:sub(1, s-1) .. suffix
  788. editor.buffer:replace(line_range, new_line)
  789. end
  790. else
  791. -- Comment (if not already commented)
  792. if not string.match(line, "^%s*" .. escaped_prefix) then
  793. local indent = string.match(line, "^%s*")
  794. local content = line:sub(#indent + 1)
  795. local new_line = indent .. prefix .. " " .. content
  796. editor.buffer:replace(line_range, new_line)
  797. end
  798. end
  799. end
  800. end
  801. else
  802. -- Single line
  803. local line_num = editor.cursor.line
  804. local line = editor.buffer:line(line_num)
  805. local line_range = lumacs.Range(lumacs.Position(line_num, 0), lumacs.Position(line_num, #line))
  806. if string.match(line, "^%s*" .. escaped_prefix) then
  807. -- Uncomment
  808. local s, e = string.find(line, escaped_prefix)
  809. if s then
  810. local suffix = line:sub(e+1)
  811. if suffix:sub(1,1) == " " then suffix = suffix:sub(2) end
  812. local new_line = line:sub(1, s-1) .. suffix
  813. editor.buffer:replace(line_range, new_line)
  814. end
  815. else
  816. -- Comment
  817. local indent = string.match(line, "^%s*")
  818. local content = line:sub(#indent + 1)
  819. local new_line = indent .. prefix .. " " .. content
  820. editor.buffer:replace(line_range, new_line)
  821. end
  822. end
  823. end
  824. editor:bind_key("M-;") comment_dwim)
  825. -- ============================================================================
  826. -- REGISTERS (C-x r s, C-x r i)
  827. -- ============================================================================
  828. -- Helper function to prompt for register character
  829. function get_register_char(prompt_msg)
  830. editor:message(prompt_msg)
  831. -- For now we'll use a simple approach - this would need UI integration
  832. -- In a full implementation, this would wait for a single character input
  833. -- For demo purposes, we'll use 'a' as default
  834. return 'a'
  835. end
  836. -- C-x r s (copy-to-register) - Save region to register
  837. editor:bind_key("C-x r s", function()
  838. local register_char = get_register_char("Save to register:")
  839. editor:copy_region_to_register(register_char)
  840. end)
  841. -- C-x r i (insert-register) - Insert from register
  842. editor:bind_key("C-x r i", function()
  843. local register_char = get_register_char("Insert register:")
  844. editor:yank_from_register(register_char)
  845. end)
  846. -- ============================================================================
  847. -- RECTANGLES (C-x r k/y/t)
  848. -- ============================================================================
  849. -- C-x r k (kill-rectangle) - Cut rectangular region
  850. editor:bind_key("C-x r k", function()
  851. editor:kill_rectangle()
  852. end)
  853. -- C-x r y (yank-rectangle) - Paste rectangular region
  854. editor:bind_key("C-x r y", function()
  855. editor:yank_rectangle()
  856. end)
  857. -- C-x r t (string-rectangle) - Fill rectangle with text
  858. editor:bind_key("C-x r t", function()
  859. -- For demo purposes, we'll fill with asterisks
  860. -- In a full implementation, this would prompt for text input
  861. editor:string_rectangle("*")
  862. editor:message("Rectangle filled with '*' - C-x r t demo")
  863. end)
  864. -- ============================================================================
  865. -- KEYBOARD MACROS (F3, F4)
  866. -- ============================================================================
  867. -- F3 - start-kbd-macro
  868. editor:bind_key("F3", function()
  869. editor:start_kbd_macro()
  870. end)
  871. -- F4 - end-kbd-macro or call-last-kbd-macro
  872. editor:bind_key("F4", function()
  873. editor:end_kbd_macro_or_call()
  874. end)
  875. -- ============================================================================
  876. -- INCREMENTAL SEARCH (C-s, C-r)
  877. -- ============================================================================
  878. -- C-s (save-buffer) - changed from isearch to save for now
  879. editor:bind_key("C-s", function()
  880. local buf = editor.buffer
  881. if buf:save() then
  882. editor:message("Buffer saved: " .. buf:name())
  883. else
  884. editor:message("Failed to save buffer")
  885. end
  886. end)
  887. -- C-r (isearch-backward)
  888. editor:bind_key("C-r", function()
  889. editor:isearch_backward_mode()
  890. end)
  891. -- Note: C-k and C-s already defined above, removed duplicates
  892. -- ============================================================================
  893. -- CONFIGURATION FUNCTIONS
  894. -- ============================================================================
  895. -- Toggle line numbers on/off
  896. function toggle_line_numbers()
  897. local config = editor.config
  898. local current = config:get_bool("show_line_numbers", true)
  899. config:set("show_line_numbers", not current)
  900. if not current then
  901. editor:message("Line numbers enabled")
  902. else
  903. editor:message("Line numbers disabled")
  904. end
  905. end
  906. -- Set line number width
  907. function set_line_number_width(width)
  908. editor.config:set("line_number_width", width)
  909. editor:message("Line number width set to " .. width)
  910. end
  911. -- Show current configuration
  912. function show_config()
  913. local config = editor.config
  914. local show_nums = config:get_bool("show_line_numbers", true)
  915. local width = config:get_int("line_number_width", 6)
  916. editor:message(string.format("Line numbers: %s, Width: %d", show_nums and "on" or "off", width))
  917. end
  918. -- Toggle modeline (status bar for each window) function
  919. function toggle_modeline()
  920. local current = editor.config:get_bool("show_modeline", true)
  921. editor.config:set_bool("show_modeline", not current)
  922. if current then
  923. editor:message("Modeline disabled")
  924. else
  925. editor:message("Modeline enabled")
  926. end
  927. end
  928. -- Bind configuration functions
  929. editor:bind_key("C-x l", toggle_line_numbers) -- C-x l to toggle line numbers
  930. editor:bind_key("C-x m", toggle_modeline) -- C-x m to toggle modeline
  931. editor:bind_key("C-x C-c", function() editor:quit() end) -- C-x C-c to quit
  932. editor:bind_key("C-x C-s", show_config) -- C-x C-s to show config
  933. -- Load theme configuration
  934. dofile("themes.lua")
  935. -- Welcome message
  936. editor: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")
  937. -- Auto-activate mode for initial buffer
  938. auto_activate_major_mode()
  939. -- File and Buffer Commands
  940. editor:register_command("save-buffer", "Save current buffer", function(args)
  941. if editor.buffer:save() then
  942. editor:message("Saved " .. editor.buffer:name())
  943. else
  944. editor:message("Save failed")
  945. end
  946. end, true, "b") -- "b" means prompt for existing buffer name
  947. editor:register_command("find-file", "Find file", function(args)
  948. editor:find_file_mode()
  949. end, true, "f") -- "f" means prompt for file name
  950. editor:register_command("kill-buffer", "Kill buffer", function(args)
  951. editor:kill_buffer_mode()
  952. end, true, "b")
  953. editor:register_command("switch-buffer", "Switch buffer", function(args)
  954. editor:buffer_switch_mode()
  955. end, true, "b")
  956. -- Alias for switch-buffer to match Emacs expectations
  957. editor:register_command("switch-to-buffer", "Switch buffer (Alias)", function(args)
  958. editor:buffer_switch_mode()
  959. end, true, "b")
  960. editor:register_command("list-buffers", "List all buffers", function(args)
  961. local buffer_info = editor:get_all_buffer_info()
  962. if #buffer_info == 0 then
  963. editor:message("No buffers open")
  964. return {success = true, message = "No buffers open"}
  965. end
  966. local lines = {}
  967. table.insert(lines, "Buffer List:")
  968. table.insert(lines, "------------")
  969. table.insert(lines, "")
  970. table.insert(lines, string.format("% -3s % -20s % -10s %s", "Mod", "Name", "Size", "File"))
  971. table.insert(lines, string.format("% -3s % -20s % -10s %s", "---", "----"))
  972. for i, info in ipairs(buffer_info) do
  973. local modified = info.modified and " * " or " "
  974. local filepath = ""
  975. if info.filepath then filepath = tostring(info.filepath) end
  976. table.insert(lines, string.format("%s % -20s % -10d %s", modified, info.name, info.size, filepath))
  977. end
  978. local list_text = table.concat(lines, "\n")
  979. local list_buf_name = "*Buffer List*"
  980. local list_buf = editor:get_buffer_by_name(list_buf_name)
  981. if list_buf then
  982. editor:switch_buffer_in_window(list_buf_name)
  983. else
  984. editor:new_buffer(list_buf_name)
  985. end
  986. editor.buffer:clear()
  987. editor.buffer:insert(lumacs.Position(0,0), list_text)
  988. editor:goto_beginning()
  989. return {success = true, message = string.format("Buffer list (%d buffers)", #buffer_info)}
  990. end, false) -- Not typically interactive through prompt
  991. -- Navigation
  992. editor:register_command("next-line", "Move cursor down", function() editor:move_down() end, true)
  993. editor:register_command("previous-line", "Move cursor up", function() editor:move_up() end, true)
  994. editor:register_command("forward-char", "Move cursor right", function() editor:move_right() end, true)
  995. editor:register_command("backward-char", "Move cursor left", function() editor:move_left() end, true)
  996. editor:register_command("forward-word", "Move forward one word", function() editor:move_forward_word() end, true)
  997. editor:register_command("backward-word", "Move backward one word", function() editor:move_backward_word() end, true)
  998. editor:register_command("beginning-of-buffer", "Go to beginning of buffer", function() editor:goto_beginning() end, true)
  999. editor:register_command("end-of-buffer", "Go to end of buffer", function() editor:goto_end() end, true)
  1000. editor:register_command("scroll-up-command", "Page down", function() editor:page_down() end, true)
  1001. editor:register_command("scroll-down-command", "Page up", function() editor:page_up() end, true)
  1002. -- Window Management
  1003. editor:register_command("split-window-below", "Split window horizontally", function() editor:split_horizontally() end, true)
  1004. editor:register_command("split-window-right", "Split window vertically", function() editor:split_vertically() end, true)
  1005. editor:register_command("delete-window", "Close current window", function() editor:close_window() end, true)
  1006. editor:register_command("other-window", "Select other window", function() editor:next_window() end, true)
  1007. editor:register_command("delete-other-windows", "Delete all other windows", function()
  1008. -- Simplified: keep closing others until only 1?
  1009. -- Or just implement properly in C++ later.
  1010. -- For now, assume users use C-x 1 if implemented?
  1011. -- C-x 1 isn't implemented in init.lua yet.
  1012. editor:message("delete-other-windows not implemented yet")
  1013. return {success = false, message = "delete-other-windows not implemented yet"}
  1014. end, false)
  1015. -- Editing
  1016. editor:register_command("kill-line", "Kill rest of line", function() editor:kill_line() end, true)
  1017. editor:register_command("kill-region", "Kill selected region", function() editor:kill_region() end, true)
  1018. editor:register_command("copy-region-as-kill", "Copy region", function() editor:copy_region_as_kill() end, true)
  1019. editor:register_command("yank", "Paste from kill ring", function() editor:yank() end, true)
  1020. editor:register_command("undo", "Undo last change", function() if editor:undo() then editor:message("Undid") else editor:message("No undo") end end, true)
  1021. editor:register_command("redo", "Redo last undo", function() if editor:redo() then editor:message("Redid") else editor:message("No redo") end end, true)
  1022. -- Modes
  1023. editor:register_command("lua-mode", "Switch to Lua mode", function() activate_major_mode("lua-mode") end, true)
  1024. editor:register_command("fundamental-mode", "Switch to Fundamental mode", function() activate_major_mode("fundamental-mode") end, true)
  1025. editor:register_command("auto-save-mode", "Toggle auto-save", function() toggle_minor_mode("auto-save-mode") end, true)
  1026. editor:message("Commands loaded. Try M-x list-buffers")
  1027. -- ============================================================================
  1028. -- NEW COMMAND SYSTEM INTEGRATION
  1029. -- ============================================================================
  1030. -- Register additional commands with the new command system
  1031. editor:register_command("describe-mode", "Show current major and minor modes", function(args)
  1032. local mode_name = current_major_mode()
  1033. local buf = editor.buffer
  1034. local buf_name = buf:name()
  1035. local minor_list = {}
  1036. if buffer_minor_modes[buf_name] then
  1037. for mode, _ in pairs(buffer_minor_modes[buf_name]) do
  1038. table.insert(minor_list, mode)
  1039. end
  1040. end
  1041. local minor_str = #minor_list > 0 and table.concat(minor_list, ", ") or "none"
  1042. return {success = true, message = string.format("Major: %s | Minor: %s", mode_name, minor_str)}
  1043. end, false)
  1044. editor:register_command("count-lines", "Count lines in buffer or region", function(args)
  1045. local buf = editor.buffer
  1046. local region = buf:get_region(editor.cursor)
  1047. if region then
  1048. local lines = region["end"].line - region.start.line + 1
  1049. return {success = true, message = string.format("Region has %d lines", lines)}
  1050. else
  1051. local lines = buf:line_count()
  1052. return {success = true, message = string.format("Buffer has %d lines", lines)}
  1053. end
  1054. end, false)
  1055. editor:register_command("word-count", "Count words in buffer or region", function(args)
  1056. local buf = editor.buffer
  1057. local region = buf:get_region(editor.cursor)
  1058. local text
  1059. if region then
  1060. text = buf:get_text_in_range(region)
  1061. else
  1062. text = buf:get_all_text()
  1063. end
  1064. local words = 0
  1065. for word in text:gmatch("%S+") do
  1066. words = words + 1
  1067. end
  1068. local target = region and "region" or "buffer"
  1069. return {success = true, message = string.format("%s has %d words", target, words)}
  1070. end, false)
  1071. editor:register_command("goto-char", "Go to character position", function(args)
  1072. if #args == 0 then
  1073. return {success = false, message = "Character position required"}
  1074. end
  1075. local pos = tonumber(args[1])
  1076. if not pos then
  1077. return {success = false, message = "Invalid character position: " .. args[1]}
  1078. end
  1079. local buf = editor.buffer
  1080. local text = buf:get_all_text()
  1081. if pos < 1 or pos > #text then
  1082. return {success = false, message = "Position out of range"}
  1083. end
  1084. -- Convert character position to line/column
  1085. local line = 0
  1086. local col = 0
  1087. for i = 1, pos - 1 do
  1088. if text:sub(i, i) == '\n' then
  1089. line = line + 1
  1090. col = 0
  1091. else
  1092. col = col + 1
  1093. end
  1094. end
  1095. editor.cursor = lumacs.Position(line, col)
  1096. return {success = true, message = string.format("Moved to character %d (line %d, column %d)", pos, line + 1, col + 1)}
  1097. end, true, "n")
  1098. editor:register_command("insert-date", "Insert current date", function(args)
  1099. local cursor_pos = editor.cursor
  1100. local timestamp = os.date("%Y-%m-%d")
  1101. editor.buffer:insert(cursor_pos, timestamp)
  1102. return {success = true, message = "Inserted current date"}
  1103. end, false)
  1104. editor:register_command("insert-datetime", "Insert current date and time", function(args)
  1105. local cursor_pos = editor.cursor
  1106. local timestamp = os.date("%Y-%m-%d %H:%M:%S")
  1107. editor.buffer:insert(cursor_pos, timestamp)
  1108. return {success = true, message = "Inserted current date and time"}
  1109. end, false)
  1110. editor:register_command("revert-buffer", "Reload buffer from file", function(args)
  1111. local buf = editor.buffer
  1112. local filepath = buf:filepath()
  1113. if not filepath then
  1114. return {success = false, message = "Buffer is not visiting a file"}
  1115. end
  1116. if buf:is_modified() then
  1117. return {success = false, message = "Buffer has unsaved changes"}
  1118. end
  1119. if editor:load_file(filepath) then
  1120. return {success = true, message = "Reverted " .. buf:name()}
  1121. else
  1122. return {success = false, message = "Failed to revert buffer"}
  1123. end
  1124. end, false)
  1125. editor:register_command("rename-buffer", "Rename current buffer", function(args)
  1126. if #args == 0 then
  1127. return {success = false, message = "New buffer name required"}
  1128. end
  1129. local new_name = args[1]
  1130. local buf = editor.buffer
  1131. local old_name = buf:name()
  1132. -- Check if name is already taken
  1133. if editor:get_buffer_by_name(new_name) then
  1134. return {success = false, message = "Buffer name already exists: " .. new_name}
  1135. end
  1136. buf:set_name(new_name)
  1137. return {success = true, message = string.format("Renamed buffer '%s' to '%s'", old_name, new_name)}
  1138. end, true, "s") -- "s" means prompt for string
  1139. -- Development commands
  1140. editor:register_command("eval-expression", "Evaluate Lua expression", function(args)
  1141. if #args == 0 then
  1142. return {success = false, message = "Lua expression required"}
  1143. end
  1144. local expr = table.concat(args, " ")
  1145. local func, err = load("return " .. expr)
  1146. if not func then
  1147. return {success = false, message = "Parse error: " .. err}
  1148. end
  1149. local success, result = pcall(func)
  1150. if success then
  1151. return {success = true, message = tostring(result)}
  1152. else
  1153. return {success = false, message = "Error: " .. tostring(result)}
  1154. end
  1155. end, true, "s")
  1156. -- Example of how to define a custom command that changes theme based on time of day
  1157. editor:register_command("auto-theme", "Automatically set theme based on time of day", function(args)
  1158. local hour = tonumber(os.date("%H"))
  1159. local theme_name
  1160. if hour >= 6 and hour < 18 then
  1161. -- Daytime: use light theme
  1162. theme_name = "gruvbox-light"
  1163. elseif hour >= 18 and hour < 22 then
  1164. -- Evening: use warm theme
  1165. theme_name = "everforest-dark"
  1166. else
  1167. -- Night: use dark theme
  1168. theme_name = "nord"
  1169. end
  1170. local success, message = editor:execute_command("set-theme", {theme_name})
  1171. if success then
  1172. return {success = true, message = string.format("Auto-selected %s theme for %d:00", theme_name, hour)}
  1173. else
  1174. return {success = false, message = "Failed to auto-select theme: " .. message}
  1175. end
  1176. end, false)
  1177. editor:register_command("theme-demo", "Demonstrate theme switching", function(args)
  1178. local themes = {"solarized-dark", "nord", "gruvbox-light", "dracula"}
  1179. local demo_msg = "Theme demo - switching through: " .. table.concat(themes, ", ")
  1180. -- This would ideally be enhanced with a timer to show themes in sequence
  1181. -- For now, just switch to a demo theme
  1182. local success, message = editor:execute_command("set-theme", {themes[1]})
  1183. if success then
  1184. return {success = true, message = demo_msg .. " (switched to " .. themes[1] .. ")"}
  1185. else
  1186. return {success = false, message = "Demo failed: " .. message}
  1187. end
  1188. end, false)
  1189. -- ============================================================================
  1190. -- COMPLETION SYSTEM (Minibuffer Auto-Complete)
  1191. -- ============================================================================
  1192. -- Returns a list of completion candidates based on the current mode and input
  1193. function get_completion_candidates(mode_name, input)
  1194. local candidates = {}
  1195. if mode_name == "Command" then
  1196. -- Command completion (M-x)
  1197. for name, _ in pairs(lumacs.command_registry) do
  1198. if name:find(input, 1, true) == 1 then -- Prefix match
  1199. table.insert(candidates, name)
  1200. end
  1201. end
  1202. table.sort(candidates)
  1203. elseif mode_name == "BufferSwitch" or mode_name == "KillBuffer" then
  1204. -- Buffer name completion
  1205. local buffers = editor:get_buffer_names()
  1206. for _, name in ipairs(buffers) do
  1207. if name:find(input, 1, true) == 1 then -- Prefix match
  1208. table.insert(candidates, name)
  1209. end
  1210. end
  1211. table.sort(candidates)
  1212. elseif mode_name == "FindFile" then
  1213. -- File path completion (simple version)
  1214. -- Note: Full file system completion is complex to do in pure Lua without bindings
  1215. -- This is a placeholder or relies on a bound helper if available.
  1216. -- For now, we'll return empty list or maybe just current directory files if exposed.
  1217. -- Since we don't have 'ls' exposed, we can't do much here yet without C++ help.
  1218. end
  1219. return candidates
  1220. end