robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
dcf36e613b
master
1" matchit.vim: (global plugin) Extended "%" matching 2" autload script of matchit plugin, see ../plugin/matchit.vim 3" Last Change: June 01, 2026 4 5" Neovim does not support scriptversion 6if has ( "vimscript-4" ) 7scriptversion 4 8endif 9 10let s: last_mps = "" 11let s: last_words = ":" 12let s: patBR = "" 13 14let s: save_cpo = & cpo 15set cpo & vim 16 17" Auto-complete mappings: (not yet "ready for prime time") 18" TODO Read :help write-plugin for the "right" way to let the user 19" specify a key binding. 20" let g:match_auto = '<C-]>' 21" let g:match_autoCR = '<C-CR>' 22" if exists("g:match_auto") 23" execute "inoremap " . g:match_auto . ' x<Esc>"=<SID>Autocomplete()<CR>Pls' 24" endif 25" if exists("g:match_autoCR") 26" execute "inoremap " . g:match_autoCR . ' <CR><C-R>=<SID>Autocomplete()<CR>' 27" endif 28" if exists("g:match_gthhoh") 29" execute "inoremap " . g:match_gthhoh . ' <C-O>:call <SID>Gthhoh()<CR>' 30" endif " gthhoh = "Get the heck out of here!" 31 32let s: notslash = '\\\@1<!\%(\\\\\)*' 33 34function s: RestoreOptions () 35" In s:CleanUp(), :execute "set" restore_options . 36let restore_options = "" 37if get ( b:, 'match_ignorecase' , & ic ) != & ic 38let restore_options ..= ( & ic ? " " : " no" ) .. "ignorecase" 39let & ignorecase = b: match_ignorecase 40endif 41if & ve != '' 42let restore_options = " ve=" .. & ve .. restore_options 43set ve = 44endif 45if & smartcase 46let restore_options = " smartcase " .. restore_options 47set nosmartcase 48endif 49return restore_options 50endfunction 51 52function matchit#Match_wrapper ( word , forward , mode ) range 53let restore_options = s: RestoreOptions () 54" In s:CleanUp(), we may need to check whether the cursor moved forward. 55let startpos = [ line ( "." ), col ( "." )] 56" if a count has been applied, use the default [count]% mode (see :h N%) 57if v: count 58exe "normal! " .. v: count .. "%" 59return s: CleanUp ( restore_options , a: mode , startpos ) 60end 61if a: mode =~# "v" && mode ( 1 ) =~# 'ni' 62exe "norm! gv" 63elseif a: mode == "o" && mode ( 1 ) !~# '[vV]' 64exe "norm! v" 65" If this function was called from Visual mode, make sure that the cursor 66" is at the correct end of the Visual range: 67elseif a: mode == "v" 68execute "normal! gv\<Esc>" 69let startpos = [ line ( "." ), col ( "." )] 70endif 71 72" Check for custom match function hook 73if exists ( "b:match_function" ) 74try 75let result = call ( b: match_function , [ a: forward ]) 76if ! empty ( result ) 77call cursor ( result ) 78return s: CleanUp ( restore_options , a: mode , startpos ) 79endif 80catch /.*/ 81if exists ( "b:match_debug" ) 82echohl WarningMsg 83echom 'matchit: b:match_function error: ' .. v: exception 84echohl NONE 85endif 86return s: CleanUp ( restore_options , a: mode , startpos ) 87endtry 88" Empty result: fall through to regular matching 89endif 90 91" First step: if not already done, set the script variables 92" s:do_BR flag for whether there are backrefs 93" s:pat parsed version of b:match_words 94" s:all regexp based on s:pat and the default groups 95if ! exists ( "b:match_words" ) || b: match_words == "" 96let match_words = "" 97elseif b: match_words =~ ":" 98let match_words = b: match_words 99else 100" Allow b:match_words = "GetVimMatchWords()" . 101execute "let match_words =" b: match_words 102endif 103" Thanks to Preben "Peppe" Guldberg and Bram Moolenaar for this suggestion! 104if ( match_words != s: last_words ) || ( & mps != s: last_mps ) 105 \|| exists ( "b:match_debug" ) 106let s: last_mps = & mps 107" quote the special chars in 'matchpairs', replace [,:] with \| and then 108" append the builtin pairs (/*, */, #if, #ifdef, #ifndef, #else, #elif, 109" #elifdef, #elifndef, #endif) 110let default = escape ( & mps , '[$^.*~\\/?]' ) .. ( strlen ( & mps ) ? "," : "" ) .. 111 \'\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\%(n\=def\)\=\>:#\s*endif\>' 112" s:all = pattern with all the keywords 113let match_words = s: Append ( match_words , default ) 114let s: last_words = match_words 115if match_words !~ s: notslash .. '\\\d' 116let s: do_BR = 0 117let s: pat = match_words 118else 119let s: do_BR = 1 120let s: pat = s: ParseWords ( match_words ) 121endif 122let s: all = substitute ( s: pat , s: notslash .. '\zs[,:]\+' , '\\|' , 'g' ) 123" un-escape \, and \: to , and : 124let s: all = substitute ( s: all , s: notslash .. '\zs\\\(:\|,\)' , '\1' , 'g' ) 125" Just in case there are too many '\(...)' groups inside the pattern, make 126" sure to use \%(...) groups, so that error E872 can be avoided 127let s: all = substitute ( s: all , s: notslash .. '\zs\\(' , '\\%(' , 'g' ) 128let s: all = '\%(' .. s: all .. '\)' 129if exists ( "b:match_debug" ) 130let b: match_pat = s: pat 131endif 132" Reconstruct the version with unresolved backrefs. 133let s: patBR = substitute ( match_words .. ',' , 134 \s: notslash .. '\zs[,:]*,[,:]*' , ',' , 'g' ) 135let s: patBR = substitute ( s: patBR , s: notslash .. '\zs:\{2,}' , ':' , 'g' ) 136" un-escape \, to , 137let s: patBR = substitute ( s: patBR , '\\,' , ',' , 'g' ) 138endif 139 140" Second step: set the following local variables: 141" matchline = line on which the cursor started 142" curcol = number of characters before match 143" prefix = regexp for start of line to start of match 144" suffix = regexp for end of match to end of line 145" Require match to end on or after the cursor and prefer it to 146" start on or before the cursor. 147let matchline = getline ( startpos [ 0 ]) 148if a: word != '' 149" word given 150if a: word !~ s: all 151echohl WarningMsg |echo 'Missing rule for word:"' . a: word . '"' |echohl NONE 152return s: CleanUp ( restore_options , a: mode , startpos ) 153endif 154let matchline = a: word 155let curcol = 0 156let prefix = '^\%(' 157let suffix = '\)$' 158" Now the case when "word" is not given 159else " Find the match that ends on or after the cursor and set curcol. 160let regexp = s: Wholematch ( matchline , s: all , startpos [ 1 ] - 1 ) 161let curcol = match ( matchline , regexp ) 162" If there is no match, give up. 163if curcol == -1 164return s: CleanUp ( restore_options , a: mode , startpos ) 165endif 166let endcol = matchend ( matchline , regexp ) 167let suf = strlen ( matchline ) - endcol 168let prefix = ( curcol ? '^.*\%' .. ( curcol + 1 ) .. 'c\%(' : '^\%(' ) 169let suffix = ( suf ? '\)\%' .. ( endcol + 1 ) .. 'c.*$' : '\)$' ) 170endif 171if exists ( "b:match_debug" ) 172let b: match_match = matchstr ( matchline , regexp ) 173let b: match_col = curcol + 1 174endif 175 176" Third step: Find the group and single word that match, and the original 177" (backref) versions of these. Then, resolve the backrefs. 178" Set the following local variable: 179" group = colon-separated list of patterns, one of which matches 180" = ini:mid:fin or ini:fin 181" 182" Now, set group and groupBR to the matching group: 'if:endif' or 183" 'while:endwhile' or whatever. A bit of a kluge: s:Choose() returns 184" group . "," . groupBR, and we pick it apart. 185let group = s: Choose ( s: pat , matchline , "," , ":" , prefix , suffix , s: patBR ) 186let i = matchend ( group , s: notslash .. "," ) 187let groupBR = strpart ( group , i ) 188let group = strpart ( group , 0 , i - 1 ) 189" Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix 190if s: do_BR " Do the hard part: resolve those backrefs! 191let group = s: InsertRefs ( groupBR , prefix , group , suffix , matchline ) 192endif 193if exists ( "b:match_debug" ) 194let b: match_wholeBR = groupBR 195let i = matchend ( groupBR , s: notslash .. ":" ) 196let b: match_iniBR = strpart ( groupBR , 0 , i - 1 ) 197endif 198 199" Fourth step: Set the arguments for searchpair(). 200let i = matchend ( group , s: notslash .. ":" ) 201let j = matchend ( group , '.*' .. s: notslash .. ":" ) 202let ini = strpart ( group , 0 , i - 1 ) 203let mid = substitute ( strpart ( group , i , j - i - 1 ), s: notslash .. '\zs:' , '\\|' , 'g' ) 204let fin = strpart ( group , j ) 205"Un-escape the remaining , and : characters. 206let ini = substitute ( ini , s: notslash .. '\zs\\\(:\|,\)' , '\1' , 'g' ) 207let mid = substitute ( mid , s: notslash .. '\zs\\\(:\|,\)' , '\1' , 'g' ) 208let fin = substitute ( fin , s: notslash .. '\zs\\\(:\|,\)' , '\1' , 'g' ) 209" searchpair() requires that these patterns avoid \(\) groups. 210let ini = substitute ( ini , s: notslash .. '\zs\\(' , '\\%(' , 'g' ) 211let mid = substitute ( mid , s: notslash .. '\zs\\(' , '\\%(' , 'g' ) 212let fin = substitute ( fin , s: notslash .. '\zs\\(' , '\\%(' , 'g' ) 213" Set mid. This is optimized for readability, not micro-efficiency! 214if a: forward && matchline =~ prefix .. fin .. suffix 215 \|| ! a: forward && matchline =~ prefix .. ini .. suffix 216let mid = "" 217endif 218" Set flag. This is optimized for readability, not micro-efficiency! 219if a: forward && matchline =~ prefix .. fin .. suffix 220 \|| ! a: forward && matchline !~ prefix .. ini .. suffix 221let flag = "bW" 222else 223let flag = "W" 224endif 225" Set skip. 226if exists ( "b:match_skip" ) 227let skip = b: match_skip 228elseif exists ( "b:match_comment" ) " backwards compatibility and testing! 229let skip = "r:" .. b: match_comment 230else 231let skip = 's:comment\|string' 232endif 233let skip = s: ParseSkip ( skip ) 234if exists ( "b:match_debug" ) 235let b: match_ini = ini 236let b: match_tail = ( strlen ( mid ) ? mid .. '\|' : '' ) .. fin 237endif 238 239" Fifth step: actually start moving the cursor and call searchpair(). 240" Later, :execute restore_cursor to get to the original screen. 241let view = winsaveview () 242call cursor ( 0 , curcol + 1 ) 243if skip =~ 'synID' && ! ( has ( "syntax" ) && exists ( "g:syntax_on" )) 244 \|| skip =~ 'v:lua.vim.treesitter' && ! exists ( 'b:ts_highlight' ) 245let skip = "0" 246else 247execute "if " .. skip .. "| let skip = '0' | endif" 248endif 249let sp_return = searchpair ( ini , mid , fin , flag , skip ) 250if & selection isnot# 'inclusive' && a: mode == 'v' 251" move cursor one pos to the right, because selection is not inclusive 252" add virtualedit=onemore, to make it work even when the match ends the 253" line 254if ! ( col ( '.' ) < col ( '$' ) - 1 ) 255let eolmark = 1 " flag to set a mark on eol (since we cannot move there) 256endif 257norm ! l 258endif 259let final_position = "call cursor(" .. line ( "." ) .. "," .. col ( "." ) .. ")" 260" Restore cursor position and original screen. 261call winrestview ( view ) 262normal ! m' 263if sp_return > 0 264execute final_position 265endif 266if exists ( 'eolmark' ) && eolmark 267call setpos ( "''" , [ 0 , line ( '.' ), col ( '$' ), 0 ]) " set mark on the eol 268endif 269return s: CleanUp ( restore_options , a: mode , startpos , mid .. '\|' .. fin ) 270endfun 271 272" Restore options and do some special handling for Operator-pending mode. 273" The optional argument is the tail of the matching group. 274fun ! s: CleanUp ( options , mode , startpos , ...) 275if strlen ( a: options ) 276execute "set" a: options 277endif 278" Open folds, if appropriate. 279if a: mode != "o" 280if & foldopen =~ "percent" 281normal ! zv 282endif 283" In Operator-pending mode, we want to include the whole match 284" (for example, d%). 285" This is only a problem if we end up moving in the forward direction. 286elseif ( a: startpos [ 0 ] < line ( "." )) || 287 \( a: startpos [ 0 ] == line ( "." ) && a: startpos [ 1 ] < col ( "." )) 288if a: 0 289" Check whether the match is a single character. If not, move to the 290" end of the match. 291let matchline = getline ( "." ) 292let currcol = col ( "." ) 293let regexp = s: Wholematch ( matchline , a: 1 , currcol - 1 ) 294let endcol = matchend ( matchline , regexp ) 295if endcol > currcol " This is NOT off by one! 296call cursor ( 0 , endcol ) 297endif 298endif " a:0 299endif " a:mode != "o" && etc. 300return 0 301endfun 302 303" Example (simplified HTML patterns): if 304" a:groupBR = '<\(\k\+\)>:</\1>' 305" a:prefix = '^.\{3}\(' 306" a:group = '<\(\k\+\)>:</\(\k\+\)>' 307" a:suffix = '\).\{2}$' 308" a:matchline = "123<tag>12" or "123</tag>12" 309" then extract "tag" from a:matchline and return "<tag>:</tag>" . 310fun ! s: InsertRefs ( groupBR , prefix , group , suffix , matchline ) 311if a: matchline !~ a: prefix .. 312 \substitute ( a: group , s: notslash .. '\zs:' , '\\|' , 'g' ) .. a: suffix 313return a: group 314endif 315let i = matchend ( a: groupBR , s: notslash .. ':' ) 316let ini = strpart ( a: groupBR , 0 , i - 1 ) 317let tailBR = strpart ( a: groupBR , i ) 318let word = s: Choose ( a: group , a: matchline , ":" , "" , a: prefix , a: suffix , 319 \a: groupBR ) 320let i = matchend ( word , s: notslash .. ":" ) 321let wordBR = strpart ( word , i ) 322let word = strpart ( word , 0 , i - 1 ) 323" Now, a:matchline =~ a:prefix . word . a:suffix 324if wordBR != ini 325let table = s: Resolve ( ini , wordBR , "table" ) 326else 327let table = "" 328let d = 0 329while d < 10 330if tailBR =~ s: notslash .. '\\' .. d 331let table = table .. d 332else 333let table = table .. "-" 334endif 335let d = d + 1 336endwhile 337endif 338let d = 9 339while d 340if table [ d ] != "-" 341let backref = substitute ( a: matchline , a: prefix .. word .. a: suffix , 342 \'\' .. table [ d ], "" ) 343" escape magic pattern metacharacters and matchit special characters [,:] 344let backref = escape ( backref , '\.*[^$~,:' ) 345execute s: Ref ( ini , d , "start" , "len" ) 346let ini = strpart ( ini , 0 , start ) .. backref .. strpart ( ini , start + len ) 347let tailBR = substitute ( tailBR , s: notslash .. '\zs\\' .. d , 348 \escape ( backref , '\\&' ), 'g' ) 349endif 350let d = d - 1 351endwhile 352if exists ( "b:match_debug" ) 353if s: do_BR 354let b: match_table = table 355let b: match_word = word 356else 357let b: match_table = "" 358let b: match_word = "" 359endif 360endif 361return ini .. ":" .. tailBR 362endfun 363 364" String append item2 to item and add ',' in between items 365fun ! s: Append ( item , item2 ) 366if a: item == '' 367return a: item2 368endif 369" there is already a trailing comma, don't add another one 370if a: item [ -1 :] == ',' 371return a: item .. a: item2 372endif 373return a: item .. ',' .. a: item2 374endfun 375 376" Input a comma-separated list of groups with backrefs, such as 377" a:groups = '\(foo\):end\1,\(bar\):end\1' 378" and return a comma-separated list of groups with backrefs replaced: 379" return '\(foo\):end\(foo\),\(bar\):end\(bar\)' 380fun ! s: ParseWords ( groups ) 381let groups = substitute ( a: groups .. "," , s: notslash .. '\zs[,:]*,[,:]*' , ',' , 'g' ) 382let groups = substitute ( groups , s: notslash .. '\zs:\{2,}' , ':' , 'g' ) 383let parsed = "" 384while groups =~ '[^,:]' 385let i = matchend ( groups , s: notslash .. ':' ) 386let j = matchend ( groups , s: notslash .. ',' ) 387let ini = strpart ( groups , 0 , i - 1 ) 388let tail = strpart ( groups , i , j - i - 1 ) .. ":" 389let groups = strpart ( groups , j ) 390let parsed = parsed .. ini 391let i = matchend ( tail , s: notslash .. ':' ) 392while i != -1 393" In 'if:else:endif', ini='if' and word='else' and then word='endif'. 394let word = strpart ( tail , 0 , i - 1 ) 395let tail = strpart ( tail , i ) 396let i = matchend ( tail , s: notslash .. ':' ) 397let parsed = parsed .. ":" .. s: Resolve ( ini , word , "word" ) 398endwhile " Now, tail has been used up. 399let parsed = parsed .. "," 400endwhile " groups =~ '[^,:]' 401let parsed = substitute ( parsed , ',$' , '' , '' ) 402return parsed 403endfun 404 405" TODO I think this can be simplified and/or made more efficient. 406" TODO What should I do if a:start is out of range? 407" Return a regexp that matches all of a:string, such that 408" matchstr(a:string, regexp) represents the match for a:pat that starts 409" as close to a:start as possible, before being preferred to after, and 410" ends after a:start . 411" Usage: 412" let regexp = s:Wholematch(getline("."), 'foo\|bar', col(".")-1) 413" let i = match(getline("."), regexp) 414" let j = matchend(getline("."), regexp) 415" let match = matchstr(getline("."), regexp) 416fun ! s: Wholematch ( string , pat , start ) 417let group = '\%(' .. a: pat .. '\)' 418let prefix = ( a: start ? '\(^.*\%<' .. ( a: start + 2 ) .. 'c\)\zs' : '^' ) 419let len = strlen ( a: string ) 420let suffix = ( a: start + 1 < len ? '\(\%>' .. ( a: start + 1 ) .. 'c.*$\)\@=' : '$' ) 421if a: string !~ prefix .. group .. suffix 422let prefix = '' 423endif 424return prefix .. group .. suffix 425endfun 426 427" No extra arguments: s:Ref(string, d) will 428" find the d'th occurrence of '\(' and return it, along with everything up 429" to and including the matching '\)'. 430" One argument: s:Ref(string, d, "start") returns the index of the start 431" of the d'th '\(' and any other argument returns the length of the group. 432" Two arguments: s:Ref(string, d, "foo", "bar") returns a string to be 433" executed, having the effect of 434" :let foo = s:Ref(string, d, "start") 435" :let bar = s:Ref(string, d, "len") 436fun ! s: Ref ( string , d , ...) 437let len = strlen ( a: string ) 438if a: d == 0 439let start = 0 440else 441let cnt = a: d 442let match = a: string 443while cnt 444let cnt = cnt - 1 445let index = matchend ( match , s: notslash .. '\\(' ) 446if index == -1 447return "" 448endif 449let match = strpart ( match , index ) 450endwhile 451let start = len - strlen ( match ) 452if a: 0 == 1 && a: 1 == "start" 453return start - 2 454endif 455let cnt = 1 456while cnt 457let index = matchend ( match , s: notslash .. '\\(\|\\)' ) - 1 458if index == -2 459return "" 460endif 461" Increment if an open, decrement if a ')': 462let cnt = cnt + ( match [ index ] == "(" ? 1 : -1 ) " ')' 463let match = strpart ( match , index + 1 ) 464endwhile 465let start = start - 2 466let len = len - start - strlen ( match ) 467endif 468if a: 0 == 1 469return len 470elseif a: 0 == 2 471return "let " .. a: 1 .. "=" .. start .. "| let " .. a: 2 .. "=" .. len 472else 473return strpart ( a: string , start , len ) 474endif 475endfun 476 477" Count the number of disjoint copies of pattern in string. 478" If the pattern is a literal string and contains no '0' or '1' characters 479" then s:Count(string, pattern, '0', '1') should be faster than 480" s:Count(string, pattern). 481fun ! s: Count ( string , pattern , ...) 482let pat = escape ( a: pattern , '\\' ) 483if a: 0 > 1 484let foo = substitute ( a: string , '[^' .. a: pattern .. ']' , "a:1" , "g" ) 485let foo = substitute ( a: string , pat , a: 2 , "g" ) 486let foo = substitute ( foo , '[^' .. a: 2 .. ']' , "" , "g" ) 487return strlen ( foo ) 488endif 489let result = 0 490let foo = a: string 491let index = matchend ( foo , pat ) 492while index != -1 493let result = result + 1 494let foo = strpart ( foo , index ) 495let index = matchend ( foo , pat ) 496endwhile 497return result 498endfun 499 500" s:Resolve('\(a\)\(b\)', '\(c\)\2\1\1\2') should return table.word, where 501" word = '\(c\)\(b\)\(a\)\3\2' and table = '-32-------'. That is, the first 502" '\1' in target is replaced by '\(a\)' in word, table[1] = 3, and this 503" indicates that all other instances of '\1' in target are to be replaced 504" by '\3'. The hard part is dealing with nesting... 505" Note that ":" is an illegal character for source and target, 506" unless it is preceded by "\". 507fun ! s: Resolve ( source , target , output ) 508let word = a: target 509let i = matchend ( word , s: notslash .. '\\\d' ) - 1 510let table = "----------" 511while i != -2 " There are back references to be replaced. 512let d = word [ i ] 513let backref = s: Ref ( a: source , d ) 514" The idea is to replace '\d' with backref. Before we do this, 515" replace any \(\) groups in backref with :1, :2, ... if they 516" correspond to the first, second, ... group already inserted 517" into backref. Later, replace :1 with \1 and so on. The group 518" number w+b within backref corresponds to the group number 519" s within a:source. 520" w = number of '\(' in word before the current one 521let w = s: Count ( 522 \substitute ( strpart ( word , 0 , i - 1 ), '\\\\' , '' , 'g' ), '\(' , '1' ) 523let b = 1 " number of the current '\(' in backref 524let s = d " number of the current '\(' in a:source 525while b <= s: Count ( substitute ( backref , '\\\\' , '' , 'g' ), '\(' , '1' ) 526 \&& s < 10 527if table [ s ] == "-" 528if w + b < 10 529" let table[s] = w + b 530let table = strpart ( table , 0 , s ) .. ( w + b ) .. strpart ( table , s + 1 ) 531endif 532let b = b + 1 533let s = s + 1 534else 535execute s: Ref ( backref , b , "start" , "len" ) 536let ref = strpart ( backref , start , len ) 537let backref = strpart ( backref , 0 , start ) .. ":" .. table [ s ] 538 \.. strpart ( backref , start + len ) 539let s = s + s: Count ( substitute ( ref , '\\\\' , '' , 'g' ), '\(' , '1' ) 540endif 541endwhile 542let word = strpart ( word , 0 , i - 1 ) .. backref .. strpart ( word , i + 1 ) 543let i = matchend ( word , s: notslash .. '\\\d' ) - 1 544endwhile 545let word = substitute ( word , s: notslash .. '\zs:' , '\\' , 'g' ) 546if a: output == "table" 547return table 548elseif a: output == "word" 549return word 550else 551return table .. word 552endif 553endfun 554 555" Assume a:comma = ",". Then the format for a:patterns and a:1 is 556" a:patterns = "<pat1>,<pat2>,..." 557" a:1 = "<alt1>,<alt2>,..." 558" If <patn> is the first pattern that matches a:string then return <patn> 559" if no optional arguments are given; return <patn>,<altn> if a:1 is given. 560fun ! s: Choose ( patterns , string , comma , branch , prefix , suffix , ...) 561let tail = ( a: patterns =~ a: comma .. "$" ? a: patterns : a: patterns .. a: comma ) 562let i = matchend ( tail , s: notslash .. a: comma ) 563if a: 0 564let alttail = ( a: 1 =~ a: comma .. "$" ? a: 1 : a: 1 .. a: comma ) 565let j = matchend ( alttail , s: notslash .. a: comma ) 566endif 567let current = strpart ( tail , 0 , i - 1 ) 568if a: branch == "" 569let currpat = current 570else 571let currpat = substitute ( current , s: notslash .. a: branch , '\\|' , 'g' ) 572endif 573" un-escape \, and \: to , and : 574let currpat = substitute ( currpat , s: notslash .. '\zs\\\(:\|,\)' , '\1' , 'g' ) 575while a: string !~ a: prefix .. currpat .. a: suffix 576let tail = strpart ( tail , i ) 577let i = matchend ( tail , s: notslash .. a: comma ) 578if i == -1 579return -1 580endif 581let current = strpart ( tail , 0 , i - 1 ) 582if a: branch == "" 583let currpat = current 584else 585let currpat = substitute ( current , s: notslash .. a: branch , '\\|' , 'g' ) 586endif 587" un-escape \, and \: to , and : 588let currpat = substitute ( currpat , s: notslash .. '\zs\\\(:\|,\)' , '\1' , 'g' ) 589if a: 0 590let alttail = strpart ( alttail , j ) 591let j = matchend ( alttail , s: notslash .. a: comma ) 592endif 593endwhile 594if a: 0 595let current = current .. a: comma .. strpart ( alttail , 0 , j - 1 ) 596endif 597return current 598endfun 599 600fun ! matchit#Match_debug () 601let b: match_debug = 1 " Save debugging information. 602" pat = all of b:match_words with backrefs parsed 603amenu &Matchit.&pat :echo b:match_pat<CR> 604" match = bit of text that is recognized as a match 605amenu &Matchit.&match :echo b:match_match<CR> 606" curcol = cursor column of the start of the matching text 607amenu &Matchit.&curcol :echo b:match_col<CR> 608" wholeBR = matching group, original version 609amenu &Matchit.wh&oleBR :echo b:match_wholeBR<CR> 610" iniBR = 'if' piece, original version 611amenu &Matchit.ini&BR :echo b:match_iniBR<CR> 612" ini = 'if' piece, with all backrefs resolved from match 613amenu &Matchit.&ini :echo b:match_ini<CR> 614" tail = 'else\|endif' piece, with all backrefs resolved from match 615amenu &Matchit.&tail :echo b:match_tail<CR> 616" fin = 'endif' piece, with all backrefs resolved from match 617amenu &Matchit.&word :echo b:match_word<CR> 618" '\'.d in ini refers to the same thing as '\'.table[d] in word. 619amenu &Matchit.t&able :echo'0:' .. b:match_table ..':9' <CR> 620endfun 621 622" Jump to the nearest unmatched "(" or "if" or "<tag>" if a:spflag == "bW" 623" or the nearest unmatched "</tag>" or "endif" or ")" if a:spflag == "W". 624" Return a "mark" for the original position, so that 625" let m = MultiMatch("bW", "n") ... call winrestview(m) 626" will return to the original position. If there is a problem, do not 627" move the cursor and return {}, unless a count is given, in which case 628" go up or down as many levels as possible and again return {}. 629" TODO This relies on the same patterns as % matching. It might be a good 630" idea to give it its own matching patterns. 631fun ! matchit#MultiMatch ( spflag , mode ) 632let restore_options = s: RestoreOptions () 633let startpos = [ line ( "." ), col ( "." )] 634" save v:count1 variable, might be reset from the restore_cursor command 635let level = v: count1 636if a: mode == "o" && mode ( 1 ) !~# '[vV]' 637exe "norm! v" 638endif 639 640" First step: if not already done, set the script variables 641" s:do_BR flag for whether there are backrefs 642" s:pat parsed version of b:match_words 643" s:all regexp based on s:pat and the default groups 644" This part is copied and slightly modified from matchit#Match_wrapper(). 645if ! exists ( "b:match_words" ) || b: match_words == "" 646let match_words = "" 647" Allow b:match_words = "GetVimMatchWords()" . 648elseif b: match_words =~ ":" 649let match_words = b: match_words 650else 651execute "let match_words =" b: match_words 652endif 653if ( match_words != s: last_words ) || ( & mps != s: last_mps ) || 654 \exists ( "b:match_debug" ) 655let default = escape ( & mps , '[$^.*~\\/?]' ) .. ( strlen ( & mps ) ? "," : "" ) .. 656 \'\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\>:#\s*endif\>' 657let s: last_mps = & mps 658let match_words = s: Append ( match_words , default ) 659let s: last_words = match_words 660if match_words !~ s: notslash .. '\\\d' 661let s: do_BR = 0 662let s: pat = match_words 663else 664let s: do_BR = 1 665let s: pat = s: ParseWords ( match_words ) 666endif 667let s: all = '\%(' .. substitute ( s: pat , '[,:]\+' , '\\|' , 'g' ) .. '\)' 668if exists ( "b:match_debug" ) 669let b: match_pat = s: pat 670endif 671" Reconstruct the version with unresolved backrefs. 672let s: patBR = substitute ( match_words .. ',' , 673 \s: notslash .. '\zs[,:]*,[,:]*' , ',' , 'g' ) 674let s: patBR = substitute ( s: patBR , s: notslash .. '\zs:\{2,}' , ':' , 'g' ) 675endif 676 677" Second step: figure out the patterns for searchpair() 678" and save the screen, cursor position, and 'ignorecase'. 679" - TODO: A lot of this is copied from matchit#Match_wrapper(). 680" - maybe even more functionality should be split off 681" - into separate functions! 682let openlist = split ( s: pat .. ',' , s: notslash .. '\zs:.\{-}' .. s: notslash .. ',' ) 683let midclolist = split ( ',' .. s: pat , s: notslash .. '\zs,.\{-}' .. s: notslash .. ':' ) 684call map ( midclolist , { ->split ( v: val , s: notslash .. ':' )}) 685let closelist = [] 686let middlelist = [] 687call map ( midclolist , { i , v ->[ extend ( closelist , v [ -1 : -1 ]), 688 \extend ( middlelist , v [ 0 : -2 ])]}) 689call map ( openlist , { i , v ->v =~# s: notslash .. '\\|' ? '\%(' .. v .. '\)' : v }) 690call map ( middlelist , { i , v ->v =~# s: notslash .. '\\|' ? '\%(' .. v .. '\)' : v }) 691call map ( closelist , { i , v ->v =~# s: notslash .. '\\|' ? '\%(' .. v .. '\)' : v }) 692let open = join ( openlist , ',' ) 693let middle = join ( middlelist , ',' ) 694let close = join ( closelist , ',' ) 695if exists ( "b:match_skip" ) 696let skip = b: match_skip 697elseif exists ( "b:match_comment" ) " backwards compatibility and testing! 698let skip = "r:" .. b: match_comment 699else 700let skip = 's:comment\|string' 701endif 702let skip = s: ParseSkip ( skip ) 703let view = winsaveview () 704 705" Third step: call searchpair(). 706" Replace '\('--but not '\\('--with '\%(' and ',' with '\|'. 707let openpat = substitute ( open , '\%(' .. s: notslash .. '\)\@<=\\(' , '\\%(' , 'g' ) 708let openpat = substitute ( openpat , ',' , '\\|' , 'g' ) 709let closepat = substitute ( close , '\%(' .. s: notslash .. '\)\@<=\\(' , '\\%(' , 'g' ) 710let closepat = substitute ( closepat , ',' , '\\|' , 'g' ) 711let middlepat = substitute ( middle , '\%(' .. s: notslash .. '\)\@<=\\(' , '\\%(' , 'g' ) 712let middlepat = substitute ( middlepat , ',' , '\\|' , 'g' ) 713 714if skip =~ 'synID' && ! ( has ( "syntax" ) && exists ( "g:syntax_on" )) 715 \|| skip =~ 'v:lua.vim.treesitter' && ! exists ( 'b:ts_highlight' ) 716let skip = '0' 717else 718try 719execute "if " .. skip .. "| let skip = '0' | endif" 720catch /^Vim\%((\a\+)\)\=:E363/ 721" We won't find anything, so skip searching, should keep Vim responsive. 722return {} 723endtry 724endif 725mark ' 726while level 727if searchpair ( openpat , middlepat , closepat , a: spflag , skip ) < 1 728call s: CleanUp ( restore_options , a: mode , startpos ) 729return {} 730endif 731let level = level - 1 732endwhile 733 734" Restore options and return a string to restore the original position. 735call s: CleanUp ( restore_options , a: mode , startpos ) 736return view 737endfun 738 739" Search backwards for "if" or "while" or "<tag>" or ... 740" and return "endif" or "endwhile" or "</tag>" or ... . 741" For now, this uses b:match_words and the same script variables 742" as matchit#Match_wrapper() . Later, it may get its own patterns, 743" either from a buffer variable or passed as arguments. 744" fun! s:Autocomplete() 745" echo "autocomplete not yet implemented :-(" 746" if !exists("b:match_words") || b:match_words == "" 747" return "" 748" end 749" let startpos = matchit#MultiMatch("bW") 750" 751" if startpos == "" 752" return "" 753" endif 754" " - TODO: figure out whether 'if' or '<tag>' matched, and construct 755" " - the appropriate closing. 756" let matchline = getline(".") 757" let curcol = col(".") - 1 758" " - TODO: Change the s:all argument if there is a new set of match pats. 759" let regexp = s:Wholematch(matchline, s:all, curcol) 760" let suf = strlen(matchline) - matchend(matchline, regexp) 761" let prefix = (curcol ? '^.\{' . curcol . '}\%(' : '^\%(') 762" let suffix = (suf ? '\).\{' . suf . '}$' : '\)$') 763" " Reconstruct the version with unresolved backrefs. 764" let patBR = substitute(b:match_words.',', '[,:]*,[,:]*', ',', 'g') 765" let patBR = substitute(patBR, ':\{2,}', ':', "g") 766" " Now, set group and groupBR to the matching group: 'if:endif' or 767" " 'while:endwhile' or whatever. 768" let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR) 769" let i = matchend(group, s:notslash . ",") 770" let groupBR = strpart(group, i) 771" let group = strpart(group, 0, i-1) 772" " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix 773" if s:do_BR 774" let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline) 775" endif 776" " let g:group = group 777" 778" " - TODO: Construct the closing from group. 779" let fake = "end" . expand("<cword>") 780" execute startpos 781" return fake 782" endfun 783 784" Close all open structures. "Get the heck out of here!" 785" fun! s:Gthhoh() 786" let close = s:Autocomplete() 787" while strlen(close) 788" put=close 789" let close = s:Autocomplete() 790" endwhile 791" endfun 792 793" Parse special strings as typical skip arguments for searchpair(): 794" s:foo becomes (current syntax item) =~ foo 795" S:foo becomes (current syntax item) !~ foo 796" r:foo becomes (line before cursor) =~ foo 797" R:foo becomes (line before cursor) !~ foo 798" t:foo becomes (current treesitter captures) =~ foo 799" T:foo becomes (current treesitter captures) !~ foo 800fun ! s: ParseSkip ( str ) 801let skip = a: str 802if skip [ 1 ] == ":" 803if skip [ 0 ] ==# "t" || skip [ 0 ] ==# "s" && & syntax != 'on' && exists ( "b:ts_highlight" ) 804let skip = "match(v:lua.vim.treesitter.get_captures_at_cursor(), '" .. strpart ( skip , 2 ) .. "') != -1" 805elseif skip [ 0 ] ==# "T" || skip [ 0 ] ==# "S" && & syntax != 'on' && exists ( "b:ts_highlight" ) 806let skip = "match(v:lua.vim.treesitter.get_captures_at_cursor(), '" .. strpart ( skip , 2 ) .. "') == -1" 807elseif skip [ 0 ] ==# "s" 808let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" .. 809 \strpart ( skip , 2 ) .. "'" 810elseif skip [ 0 ] ==# "S" 811let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" .. 812 \strpart ( skip , 2 ) .. "'" 813elseif skip [ 0 ] ==# "r" 814let skip = "strpart(getline('.'),0,col('.'))=~'" .. strpart ( skip , 2 ) .. "'" 815elseif skip [ 0 ] ==# "R" 816let skip = "strpart(getline('.'),0,col('.'))!~'" .. strpart ( skip , 2 ) .. "'" 817endif 818endif 819return skip 820endfun 821 822let & cpo = s: save_cpo 823unlet s: save_cpo 824 825" vim:sts=2:sw=2:et: