robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1---@class vim._comment.Parts 2---@field left string Left part of comment 3---@field right string Right part of comment 4 5--- Get 'commentstring' at cursor 6---@param ref_position [integer,integer] 7---@return string 8local function get_commentstring ( ref_position ) 9local buf_cs =vim . bo . commentstring 10 11local ts_parser =vim . treesitter . get_parser ( 0 , '' ) 12if not ts_parser then 13return buf_cs 14end 15 16-- Try to get 'commentstring' associated with local tree-sitter language. 17-- This is useful for injected languages (like markdown with code blocks). 18local row , col =ref_position [ 1 ] - 1 , ref_position [ 2 ] 19local ref_range ={ row , col , row , col + 1 } 20 21-- Get 'commentstring' from tree-sitter captures' metadata. 22-- Traverse backwards to prefer narrower captures. 23local caps =vim . treesitter . get_captures ( 0 , { row , col } ) 24for i =# caps , 1 , - 1 do 25local id , metadata =caps [ i ]. id , caps [ i ]. metadata 26local md_cms =metadata [ 'bo.commentstring' ] or metadata [ id ] and metadata [ id ][ 'bo.commentstring' ] 27 28if md_cms then 29return md_cms 30end 31end 32 33-- - Get 'commentstring' from the deepest LanguageTree which both contains 34-- reference range and has valid 'commentstring' (meaning it has at least 35-- one associated 'filetype' with valid 'commentstring'). 36-- In simple cases using `parser:language_for_range()` would be enough, but 37-- it fails for languages without valid 'commentstring' (like 'comment'). 38local ts_cs , res_level =nil , 0 39 40---@param lang_tree vim.treesitter.LanguageTree 41---@param level integer 42local function traverse ( lang_tree , level ) 43if not lang_tree : contains ( ref_range ) then 44return 45end 46 47local lang =lang_tree : lang () 48local filetypes =vim . treesitter . language . get_filetypes ( lang ) 49for _ , ft in ipairs ( filetypes ) do 50local cur_cs =vim . filetype . get_option ( ft , 'commentstring' ) 51if cur_cs ~= '' and level > res_level then 52ts_cs =cur_cs 53end 54end 55 56for _ , child_lang_tree in pairs ( lang_tree : children ()) do 57traverse ( child_lang_tree , level + 1 ) 58end 59end 60traverse ( ts_parser , 1 ) 61 62return ts_cs or buf_cs 63end 64 65--- Compute comment parts from 'commentstring' 66---@param ref_position [integer,integer] 67---@return vim._comment.Parts 68local function get_comment_parts ( ref_position ) 69local cs =get_commentstring ( ref_position ) 70 71if cs == nil or cs == '' then 72vim . api . nvim_echo ( { { "Option 'commentstring' is empty." , 'WarningMsg' } } , true ) 73return { left ='' , right ='' } 74end 75 76if not ( type ( cs ) == 'string' and cs : find ( '%%s' ) ~= nil ) then 77error ( vim . inspect ( cs ) .. " is not a valid 'commentstring'." ) 78end 79 80-- Structure of 'commentstring': <left part> <%s> <right part> 81local left , right =cs : match ( '^(.-)%%s(.-)$' ) 82assert ( left and right ) 83return { left =left , right =right } 84end 85 86--- Make a function that checks if a line is commented 87---@param parts vim._comment.Parts 88---@return fun(line: string): boolean 89local function make_comment_check ( parts ) 90local l_esc , r_esc =vim . pesc ( parts . left ), vim . pesc ( parts . right ) 91 92-- Commented line has the following structure: 93-- <whitespace> <trimmed left> <anything> <trimmed right> <whitespace> 94local regex ='^%s-' .. vim . trim ( l_esc ) .. '.*' .. vim . trim ( r_esc ) .. '%s-$' 95 96return function ( line ) 97return line : find ( regex ) ~= nil 98end 99end 100 101--- Compute comment-related information about lines 102---@param lines string[] 103---@param parts vim._comment.Parts 104---@return string indent 105---@return boolean is_commented 106local function get_lines_info ( lines , parts ) 107local comment_check =make_comment_check ( parts ) 108 109local is_commented =true 110local indent_width =math . huge 111---@type string 112local indent 113 114for _ , l in ipairs ( lines ) do 115-- Update lines indent: minimum of all indents except blank lines 116local _ , indent_width_cur , indent_cur =l : find ( '^(%s*)' ) 117assert ( indent_width_cur and indent_cur ) 118 119-- Ignore blank lines completely when making a decision 120if indent_width_cur < l : len () then 121-- NOTE: Copying actual indent instead of recreating it with `indent_width` 122-- allows to handle both tabs and spaces 123if indent_width_cur < indent_width then 124---@diagnostic disable-next-line:cast-local-type 125indent_width , indent =indent_width_cur , indent_cur 126end 127 128-- Update comment info: commented if every non-blank line is commented 129if is_commented then 130is_commented =comment_check ( l ) 131end 132end 133end 134 135-- `indent` can still be `nil` in case all `lines` are empty 136return indent or '' , is_commented 137end 138 139--- Compute whether a string is blank 140---@param x string 141---@return boolean is_blank 142local function is_blank ( x ) 143return x : find ( '^%s*$' ) ~= nil 144end 145 146--- Make a function which comments a line 147---@param parts vim._comment.Parts 148---@param indent string 149---@return fun(line: string): string 150local function make_comment_function ( parts , indent ) 151local prefix , nonindent_start , suffix =indent .. parts . left , indent : len () + 1 , parts . right 152local blank_comment =indent .. vim . trim ( parts . left ) .. vim . trim ( suffix ) 153 154return function ( line ) 155if is_blank ( line ) then 156return blank_comment 157end 158return prefix .. line : sub ( nonindent_start ) .. suffix 159end 160end 161 162--- Make a function which uncomments a line 163---@param parts vim._comment.Parts 164---@return fun(line: string): string 165local function make_uncomment_function ( parts ) 166local l_esc , r_esc =vim . pesc ( parts . left ), vim . pesc ( parts . right ) 167local regex ='^(%s*)' .. l_esc .. '(.*)' .. r_esc .. '(%s-)$' 168local regex_trimmed ='^(%s*)' .. vim . trim ( l_esc ) .. '(.*)' .. vim . trim ( r_esc ) .. '(%s-)$' 169 170return function ( line ) 171-- Try regex with exact comment parts first, fall back to trimmed parts 172local indent , new_line , trail =line : match ( regex ) 173if new_line == nil then 174indent , new_line , trail =line : match ( regex_trimmed ) 175end 176 177-- Return original if line is not commented 178if new_line == nil then 179return line 180end 181 182-- Prevent trailing whitespace 183if is_blank ( new_line ) then 184indent , trail ='' , '' 185end 186 187return indent .. new_line .. trail 188end 189end 190 191--- Comment/uncomment buffer range 192---@param line_start integer 193---@param line_end integer 194---@param ref_position? [integer, integer] 195local function toggle_lines ( line_start , line_end , ref_position ) 196ref_position =ref_position or { line_start , 0 } 197local parts =get_comment_parts ( ref_position ) 198local lines =vim . api . nvim_buf_get_lines ( 0 , line_start - 1 , line_end , false ) 199local indent , is_comment =get_lines_info ( lines , parts ) 200 201local f =is_comment and make_uncomment_function ( parts ) or make_comment_function ( parts , indent ) 202 203-- Direct `nvim_buf_set_lines()` essentially removes both regular and 204-- extended marks (squashes to empty range at either side of the region) 205-- inside region. Use 'lockmarks' to preserve regular marks. 206-- Preserving extmarks is not a universally good thing to do: 207-- - Good for non-highlighting in text area extmarks (like showing signs). 208-- - Debatable for highlighting in text area (like LSP semantic tokens). 209-- Mostly because it causes flicker as highlighting is preserved during 210-- comment toggling. 211vim . _with ( { lockmarks =true } , function () 212vim . api . nvim_buf_set_lines ( 0 , line_start - 1 , line_end , false , vim . tbl_map ( f , lines )) 213end ) 214end 215 216--- Operator which toggles user-supplied range of lines 217---@param mode string? 218---|"'line'" 219---|"'char'" 220---|"'block'" 221local function operator ( mode ) 222-- Used without arguments as part of expression mapping. Otherwise it is 223-- called as 'operatorfunc'. 224if mode == nil then 225vim . o . operatorfunc =operator 226return 'g@' 227end 228 229-- Compute target range 230local mark_from , mark_to ="'[" , "']" 231local lnum_from , col_from =vim . fn . line ( mark_from ), vim . fn . col ( mark_from ) 232local lnum_to , col_to =vim . fn . line ( mark_to ), vim . fn . col ( mark_to ) 233 234-- Do nothing if "from" mark is after "to" (like in empty textobject) 235if ( lnum_from > lnum_to ) or ( lnum_from == lnum_to and col_from > col_to ) then 236return 237end 238 239-- NOTE: use cursor position as reference for possibly computing local 240-- tree-sitter-based 'commentstring'. Recompute every time for a proper 241-- dot-repeat. In Visual and sometimes Normal mode it uses start position. 242toggle_lines ( lnum_from , lnum_to , vim . api . nvim_win_get_cursor ( 0 )) 243return '' 244end 245 246--- Select contiguous commented lines at cursor 247local function textobject () 248local lnum_cur =vim . fn . line ( '.' ) 249local parts =get_comment_parts ( { lnum_cur , vim . fn . col ( '.' ) } ) 250local comment_check =make_comment_check ( parts ) 251 252if not comment_check ( vim . fn . getline ( lnum_cur )) then 253return 254end 255 256-- Compute commented range 257local lnum_from =lnum_cur 258while ( lnum_from >= 2 ) and comment_check ( vim . fn . getline ( lnum_from - 1 )) do 259lnum_from =lnum_from - 1 260end 261 262local lnum_to =lnum_cur 263local n_lines =vim . api . nvim_buf_line_count ( 0 ) 264while ( lnum_to <= n_lines - 1 ) and comment_check ( vim . fn . getline ( lnum_to + 1 )) do 265lnum_to =lnum_to + 1 266end 267 268-- Select range linewise for operator to act upon 269vim . cmd ( 'normal! ' .. lnum_from .. 'GV' .. lnum_to .. 'G' ) 270end 271 272return { operator =operator , textobject =textobject , toggle_lines =toggle_lines }