3 local util = import("micro/util")
4 local config = import("micro/config")
5 local buffer = import("micro/buffer")
13 ft["python3"] = "# %s"
14 ft["html"] = "<!-- %s -->"
22 ft["javascript"] = "// %s"
27 function onBufferOpen(buf)
28 if buf.Settings["commenttype"] == nil then
29 if ft[buf.Settings["filetype"]] ~= nil then
30 buf.Settings["commenttype"] = ft[buf.Settings["filetype"]]
32 buf.Settings["commenttype"] = "# %s"
37 function commentLine(bp, lineN)
38 local line = bp.Buf:Line(lineN)
39 local commentType = bp.Buf.Settings["commenttype"]
40 local commentRegex = "^%s*" .. commentType:gsub("%*", "%*"):gsub("%-", "%-"):gsub("%.", "%."):gsub("%+", "%+"):gsub("%]", "%]"):gsub("%[", "%["):gsub("%%s", "(.*)")
41 local sel = -bp.Cursor.CurSelection
42 local curpos = -bp.Cursor.Loc
43 local index = string.find(commentType, "%%s") - 1
44 if string.match(line, commentRegex) then
45 uncommentedLine = string.match(line, commentRegex)
46 bp.Buf:Replace(buffer.Loc(0, lineN), buffer.Loc(#line, lineN), util.GetLeadingWhitespace(line) .. uncommentedLine)
47 if bp.Cursor:HasSelection() then
48 bp.Cursor.CurSelection[1].Y = sel[1].Y
49 bp.Cursor.CurSelection[2].Y = sel[2].Y
50 bp.Cursor.CurSelection[1].X = sel[1].X
51 bp.Cursor.CurSelection[2].X = sel[2].X
53 bp.Cursor.X = curpos.X - index
54 bp.Cursor.Y = curpos.Y
57 local commentedLine = commentType:gsub("%%s", trim(line))
58 bp.Buf:Replace(buffer.Loc(0, lineN), buffer.Loc(#line, lineN), util.GetLeadingWhitespace(line) .. commentedLine)
59 if bp.Cursor:HasSelection() then
60 bp.Cursor.CurSelection[1].Y = sel[1].Y
61 bp.Cursor.CurSelection[2].Y = sel[2].Y
62 bp.Cursor.CurSelection[1].X = sel[1].X
63 bp.Cursor.CurSelection[2].X = sel[2].X
65 bp.Cursor.X = curpos.X + index
66 bp.Cursor.Y = curpos.Y
70 bp.Cursor.LastVisualX = bp.Cursor:GetVisualX()
73 function commentSelection(bp, startLine, endLine)
74 for line = startLine, endLine do
79 function comment(bp, args)
80 if bp.Cursor:HasSelection() then
81 if bp.Cursor.CurSelection[1]:GreaterThan(-bp.Cursor.CurSelection[2]) then
82 local endLine = bp.Cursor.CurSelection[1].Y
83 if bp.Cursor.CurSelection[1].X == 0 then
86 commentSelection(bp, bp.Cursor.CurSelection[2].Y, endLine)
88 local endLine = bp.Cursor.CurSelection[2].Y
89 if bp.Cursor.CurSelection[2].X == 0 then
92 commentSelection(bp, bp.Cursor.CurSelection[1].Y, endLine)
95 commentLine(bp, bp.Cursor.Y)
100 return (s:gsub("^%s*(.-)%s*$", "%1"))
103 function string.starts(String,Start)
104 return string.sub(String,1,string.len(Start))==Start
108 config.MakeCommand("comment", "comment.comment", config.NoComplete)
109 config.TryBindKey("Alt-/", "lua:comment.comment", false)
110 config.AddRuntimeFile("comment", config.RTHelp, "help/comment.md")