init.lua 49 KB

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