robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
7f8175dc48
master
1" Vim indent script for HTML 2" Maintainer: The Vim Project <https://github.com/vim/vim> 3" Original Author: Andy Wokula <anwoku@yahoo.de> 4" Last Change: 2025 Apr 13 5" Version: 1.0 "{{{ 6" Description: HTML indent script with cached state for faster indenting on a 7" range of lines. 8" Supports template systems through hooks. 9" Supports Closure stylesheets. 10" 11" Credits: 12" indent/html.vim (2006 Jun 05) from J. Zellner 13" indent/css.vim (2006 Dec 20) from N. Weibull 14" 15" History: 16" 2014 June (v1.0) overhaul (Bram) 17" 2012 Oct 21 (v0.9) added support for shiftwidth() 18" 2011 Sep 09 (v0.8) added HTML5 tags (thx to J. Zuckerman) 19" 2008 Apr 28 (v0.6) revised customization 20" 2008 Mar 09 (v0.5) fixed 'indk' issue (thx to C.J. Robinson) 21"}}} 22 23" Init Folklore, check user settings (2nd time ++) 24if exists ( "b:did_indent" ) "{{{ 25finish 26endif 27 28" Load the Javascript indent script first, it defines GetJavascriptIndent(). 29" Undo the rest. 30" Load base python indent. 31if ! exists ( '*GetJavascriptIndent' ) 32runtime ! indent/javascript.vim 33endif 34let b: did_indent = 1 35 36setlocal indentexpr = HtmlIndent () 37setlocal indentkeys = o,O,<Return>,<>>,{,},!^F 38 39" Needed for % to work when finding start/end of a tag. 40setlocal matchpairs += <:> 41 42let b: undo_indent = "setlocal inde< indk<" 43 44" b:hi_indent keeps state to speed up indenting consecutive lines. 45let b: hi_indent = { "lnum" : -1 } 46 47"""""" Code below this is loaded only once. """"" 48if exists ( "*HtmlIndent" ) && ! exists ( 'g:force_reload_html' ) 49call HtmlIndent_CheckUserSettings () 50finish 51endif 52 53" Allow for line continuation below. 54let s: cpo_save = & cpo 55set cpo -= C 56"}}} 57 58" Pattern to match the name of a tag, including custom elements. 59let s: tagname = '\w\+\(-\w\+\)*' 60 61" Check and process settings from b:html_indent and g:html_indent... variables. 62" Prefer using buffer-local settings over global settings, so that there can 63" be defaults for all HTML files and exceptions for specific types of HTML 64" files. 65func HtmlIndent_CheckUserSettings () 66"{{{ 67let inctags = '' 68if exists ( "b:html_indent_inctags" ) 69let inctags = b: html_indent_inctags 70elseif exists ( "g:html_indent_inctags" ) 71let inctags = g: html_indent_inctags 72endif 73let b: hi_tags = {} 74if len ( inctags ) > 0 75call s: AddITags ( b: hi_tags , split ( inctags , "," )) 76endif 77 78let autotags = '' 79if exists ( "b:html_indent_autotags" ) 80let autotags = b: html_indent_autotags 81elseif exists ( "g:html_indent_autotags" ) 82let autotags = g: html_indent_autotags 83endif 84let b: hi_removed_tags = {} 85if len ( autotags ) > 0 86call s: RemoveITags ( b: hi_removed_tags , split ( autotags , "," )) 87endif 88 89" Syntax names indicating being inside a string of an attribute value. 90let string_names = [] 91if exists ( "b:html_indent_string_names" ) 92let string_names = b: html_indent_string_names 93elseif exists ( "g:html_indent_string_names" ) 94let string_names = g: html_indent_string_names 95endif 96let b: hi_insideStringNames = [ 'htmlString' ] 97if len ( string_names ) > 0 98for s in string_names 99call add ( b: hi_insideStringNames , s ) 100endfor 101endif 102 103" Syntax names indicating being inside a tag. 104let tag_names = [] 105if exists ( "b:html_indent_tag_names" ) 106let tag_names = b: html_indent_tag_names 107elseif exists ( "g:html_indent_tag_names" ) 108let tag_names = g: html_indent_tag_names 109endif 110let b: hi_insideTagNames = [ 'htmlTag' , 'htmlScriptTag' ] 111if len ( tag_names ) > 0 112for s in tag_names 113call add ( b: hi_insideTagNames , s ) 114endfor 115endif 116 117let indone = { "zero" : 0 118 \, "auto" : "indent(prevnonblank(v:lnum-1))" 119 \, "inc" : "b:hi_indent.blocktagind + shiftwidth()" } 120 121let script1 = '' 122if exists ( "b:html_indent_script1" ) 123let script1 = b: html_indent_script1 124elseif exists ( "g:html_indent_script1" ) 125let script1 = g: html_indent_script1 126endif 127if len ( script1 ) > 0 128let b: hi_js1indent = get ( indone , script1 , indone . zero ) 129else 130let b: hi_js1indent = 0 131endif 132 133let style1 = '' 134if exists ( "b:html_indent_style1" ) 135let style1 = b: html_indent_style1 136elseif exists ( "g:html_indent_style1" ) 137let style1 = g: html_indent_style1 138endif 139if len ( style1 ) > 0 140let b: hi_css1indent = get ( indone , style1 , indone . zero ) 141else 142let b: hi_css1indent = 0 143endif 144 145if ! exists ( 'b:html_indent_line_limit' ) 146if exists ( 'g:html_indent_line_limit' ) 147let b: html_indent_line_limit = g: html_indent_line_limit 148else 149let b: html_indent_line_limit = 200 150endif 151endif 152 153if exists ( 'b:html_indent_attribute' ) 154let b: hi_attr_indent = b: html_indent_attribute 155elseif exists ( 'g:html_indent_attribute' ) 156let b: hi_attr_indent = g: html_indent_attribute 157else 158let b: hi_attr_indent = 2 159endif 160 161endfunc "}}} 162 163" Init Script Vars 164"{{{ 165let b: hi_lasttick = 0 166let b: hi_newstate = {} 167let s: countonly = 0 168"}}} 169 170" Fill the s:indent_tags dict with known tags. 171" The key is "tagname" or "/tagname". {{{ 172" The value is: 173" 1 opening tag 174" 2 "pre" 175" 3 "script" 176" 4 "style" 177" 5 comment start 178" 6 conditional comment start 179" -1 closing tag 180" -2 "/pre" 181" -3 "/script" 182" -4 "/style" 183" -5 comment end 184" -6 conditional comment end 185let s: indent_tags = {} 186let s: endtags = [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] " long enough for the highest index 187"}}} 188 189" Add a list of tag names for a pair of <tag> </tag> to "tags". 190func s: AddITags ( tags , taglist ) 191"{{{ 192for itag in a: taglist 193let a: tags [ itag ] = 1 194let a: tags [ '/' . itag ] = -1 195endfor 196endfunc "}}} 197 198" Take a list of tag name pairs that are not to be used as tag pairs. 199func s: RemoveITags ( tags , taglist ) 200"{{{ 201for itag in a: taglist 202let a: tags [ itag ] = 1 203let a: tags [ '/' . itag ] = 1 204endfor 205endfunc "}}} 206 207" Add a block tag, that is a tag with a different kind of indenting. 208func s: AddBlockTag ( tag , id , ...) 209"{{{ 210if ! ( a: id >= 2 && a: id < len ( s: endtags )) 211echoerr 'AddBlockTag ' . a: id 212return 213endif 214let s: indent_tags [ a: tag ] = a: id 215if a: 0 == 0 216let s: indent_tags [ '/' . a: tag ] = - a: id 217let s: endtags [ a: id ] = "</" . a: tag . ">" 218else 219let s: indent_tags [ a: 1 ] = - a: id 220let s: endtags [ a: id ] = a: 1 221endif 222endfunc "}}} 223 224" Add known tag pairs. 225" Self-closing tags and tags that are sometimes {{{ 226" self-closing (e.g., <p>) are not here (when encountering </p> we can find 227" the matching <p>, but not the other way around). 228" Known self-closing tags: " 'p', 'img', 'source', 'area', 'keygen', 'track', 229" 'wbr'. 230" Old HTML tags: 231call s: AddITags ( s: indent_tags , [ 232 \'a' , 'abbr' , 'acronym' , 'address' , 'b' , 'bdo' , 'big' , 233 \'blockquote' , 'body' , 'button' , 'caption' , 'center' , 'cite' , 'code' , 234 \'colgroup' , 'dd' , 'del' , 'dfn' , 'dir' , 'div' , 'dl' , 'dt' , 'em' , 'fieldset' , 'font' , 235 \'form' , 'frameset' , 'h1' , 'h2' , 'h3' , 'h4' , 'h5' , 'h6' , 'head' , 'html' , 236 \'i' , 'iframe' , 'ins' , 'kbd' , 'label' , 'legend' , 'li' , 237 \'map' , 'menu' , 'noframes' , 'noscript' , 'object' , 'ol' , 238 \'optgroup' , 'q' , 's' , 'samp' , 'select' , 'small' , 'span' , 'strong' , 'sub' , 239 \'sup' , 'table' , 'textarea' , 'title' , 'tt' , 'u' , 'ul' , 'var' , 'th' , 'td' , 240 \'tr' , 'tbody' , 'tfoot' , 'thead' ]) 241 242" New HTML5 elements: 243call s: AddITags ( s: indent_tags , [ 244 \'article' , 'aside' , 'audio' , 'bdi' , 'canvas' , 'command' , 'data' , 245 \'datalist' , 'details' , 'dialog' , 'embed' , 'figcaption' , 'figure' , 246 \'footer' , 'header' , 'hgroup' , 'main' , 'mark' , 'meter' , 'nav' , 'output' , 247 \'picture' , 'progress' , 'rp' , 'rt' , 'ruby' , 'section' , 'summary' , 248 \'svg' , 'time' , 'video' ]) 249 250" Tags added for web components: 251call s: AddITags ( s: indent_tags , [ 252 \'content' , 'shadow' , 'template' ]) 253"}}} 254 255" Add Block Tags: these contain alien content 256"{{{ 257call s: AddBlockTag ( 'pre' , 2 ) 258call s: AddBlockTag ( 'script' , 3 ) 259call s: AddBlockTag ( 'style' , 4 ) 260call s: AddBlockTag ( '<!--' , 5 , '-->' ) 261call s: AddBlockTag ( '<!--[' , 6 , '![endif]-->' ) 262"}}} 263 264" Return non-zero when "tagname" is an opening tag, not being a block tag, for 265" which there should be a closing tag. Can be used by scripts that include 266" HTML indenting. 267func HtmlIndent_IsOpenTag ( tagname ) 268"{{{ 269if get ( s: indent_tags , a: tagname ) == 1 270return 1 271endif 272return get ( b: hi_tags , a: tagname ) == 1 273endfunc "}}} 274 275" Get the value for "tagname", taking care of buffer-local tags. 276func s: get_tag ( tagname ) 277"{{{ 278let i = get ( s: indent_tags , a: tagname ) 279if ( i == 1 || i == -1 ) && get ( b: hi_removed_tags , a: tagname ) != 0 280return 0 281endif 282if i == 0 283let i = get ( b: hi_tags , a: tagname ) 284endif 285return i 286endfunc "}}} 287 288" Count the number of start and end tags in "text". 289func s: CountITags ( text ) 290"{{{ 291" Store the result in s:curind and s:nextrel. 292let s: curind = 0 " relative indent steps for current line [unit &sw]: 293let s: nextrel = 0 " relative indent steps for next line [unit &sw]: 294let s: block = 0 " assume starting outside of a block 295let s: countonly = 1 " don't change state 296call substitute ( a: text , '<\zs/\=' . s: tagname . '\>\|<!--\[\|\[endif\]-->\|<!--\|-->' , '\=s:CheckTag(submatch(0))' , 'g' ) 297let s: countonly = 0 298endfunc "}}} 299 300" Count the number of start and end tags in text. 301func s: CountTagsAndState ( text ) 302"{{{ 303" Store the result in s:curind and s:nextrel. Update b:hi_newstate.block. 304let s: curind = 0 " relative indent steps for current line [unit &sw]: 305let s: nextrel = 0 " relative indent steps for next line [unit &sw]: 306 307let s: block = b: hi_newstate . block 308let tmp = substitute ( a: text , '<\zs/\=' . s: tagname . '\>\|<!--\[\|\[endif\]-->\|<!--\|-->' , '\=s:CheckTag(submatch(0))' , 'g' ) 309if s: block == 3 310let b: hi_newstate . scripttype = s: GetScriptType ( matchstr ( tmp , '\C.*<SCRIPT\>\zs[^>]*' )) 311endif 312let b: hi_newstate . block = s: block 313endfunc "}}} 314 315" Used by s:CountITags() and s:CountTagsAndState(). 316func s: CheckTag ( itag ) 317"{{{ 318" Returns an empty string or "SCRIPT". 319" a:itag can be "tag" or "/tag" or "<!--" or "-->" 320if ( s: CheckCustomTag ( a: itag )) 321return "" 322endif 323let ind = s: get_tag ( a: itag ) 324if ind == -1 325" closing tag 326if s: block != 0 327" ignore itag within a block 328return "" 329endif 330if s: nextrel == 0 331let s: curind -= 1 332else 333let s: nextrel -= 1 334endif 335elseif ind == 1 336" opening tag 337if s: block != 0 338return "" 339endif 340let s: nextrel += 1 341elseif ind != 0 342" block-tag (opening or closing) 343return s: CheckBlockTag ( a: itag , ind ) 344" else ind==0 (other tag found): keep indent 345endif 346return "" 347endfunc "}}} 348 349" Used by s:CheckTag(). Returns an empty string or "SCRIPT". 350func s: CheckBlockTag ( blocktag , ind ) 351"{{{ 352if a: ind > 0 353" a block starts here 354if s: block != 0 355" already in a block (nesting) - ignore 356" especially ignore comments after other blocktags 357return "" 358endif 359let s: block = a: ind " block type 360if s: countonly 361return "" 362endif 363let b: hi_newstate . blocklnr = v: lnum 364" save allover indent for the endtag 365let b: hi_newstate . blocktagind = b: hi_indent . baseindent + ( s: nextrel + s: curind ) * shiftwidth () 366if a: ind == 3 367return "SCRIPT" " all except this must be lowercase 368" line is to be checked again for the type attribute 369endif 370else 371let s: block = 0 372" we get here if starting and closing a block-tag on the same line 373endif 374return "" 375endfunc "}}} 376 377" Used by s:CheckTag(). 378func s: CheckCustomTag ( ctag ) 379"{{{ 380" Returns 1 if ctag is the tag for a custom element, 0 otherwise. 381" a:ctag can be "tag" or "/tag" or "<!--" or "-->" 382let pattern = '\%\(\w\+-\)\+\w\+' 383if match ( a: ctag , pattern ) == -1 384return 0 385endif 386if matchstr ( a: ctag , '\/\ze.\+' ) == "/" 387" closing tag 388if s: block != 0 389" ignore ctag within a block 390return 1 391endif 392if s: nextrel == 0 393let s: curind -= 1 394else 395let s: nextrel -= 1 396endif 397else 398" opening tag 399if s: block != 0 400return 1 401endif 402let s: nextrel += 1 403endif 404return 1 405endfunc "}}} 406 407" Return the <script> type: either "javascript" or "" 408func s: GetScriptType ( str ) 409"{{{ 410if a: str == "" || a: str =~ "java" 411return "javascript" 412else 413return "" 414endif 415endfunc "}}} 416 417" Look back in the file, starting at a:lnum - 1, to compute a state for the 418" start of line a:lnum. Return the new state. 419func s: FreshState ( lnum ) 420"{{{ 421" A state is to know ALL relevant details about the 422" lines 1..a:lnum-1, initial calculating (here!) can be slow, but updating is 423" fast (incremental). 424" TODO: this should be split up in detecting the block type and computing the 425" indent for the block type, so that when we do not know the indent we do 426" not need to clear the whole state and re-detect the block type again. 427" State: 428" lnum last indented line == prevnonblank(a:lnum - 1) 429" block = 0 a:lnum located within special tag: 0:none, 2:<pre>, 430" 3:<script>, 4:<style>, 5:<!--, 6:<!--[ 431" baseindent use this indent for line a:lnum as a start - kind of 432" autoindent (if block==0) 433" scripttype = '' type attribute of a script tag (if block==3) 434" blocktagind indent for current opening (get) and closing (set) 435" blocktag (if block!=0) 436" blocklnr lnum of starting blocktag (if block!=0) 437" inattr line {lnum} starts with attributes of a tag 438let state = {} 439let state . lnum = prevnonblank ( a: lnum - 1 ) 440let state . scripttype = "" 441let state . blocktagind = -1 442let state . block = 0 443let state . baseindent = 0 444let state . blocklnr = 0 445let state . inattr = 0 446 447if state . lnum == 0 448return state 449endif 450 451" Heuristic: 452" remember startline state.lnum 453" look back for <pre, </pre, <script, </script, <style, </style tags 454" remember stopline 455" if opening tag found, 456" assume a:lnum within block 457" else 458" look back in result range (stopline, startline) for comment 459" \ delimiters (<!--, -->) 460" if comment opener found, 461" assume a:lnum within comment 462" else 463" assume usual html for a:lnum 464" if a:lnum-1 has a closing comment 465" look back to get indent of comment opener 466" FI 467 468" look back for a blocktag 469let stopline2 = v: lnum + 1 470if has_key ( b: hi_indent , 'block' ) && b: hi_indent . block > 5 471let [ stopline2 , stopcol2 ] = searchpos ( '<!--' , 'bnW' ) 472endif 473let [ stopline , stopcol ] = searchpos ( '\c<\zs\/\=\%(pre\>\|script\>\|style\>\)' , "bnW" ) 474if stopline > 0 && stopline < stopline2 475" ugly ... why isn't there searchstr() 476let tagline = tolower ( getline ( stopline )) 477let blocktag = matchstr ( tagline , '\/\=\%(pre\>\|script\>\|style\>\)' , stopcol - 1 ) 478if blocktag [ 0 ] != "/" 479" opening tag found, assume a:lnum within block 480let state . block = s: indent_tags [ blocktag ] 481if state . block == 3 482let state . scripttype = s: GetScriptType ( matchstr ( tagline , '\>[^>]*' , stopcol )) 483endif 484let state . blocklnr = stopline 485" check preceding tags in the line: 486call s: CountITags ( tagline [: stopcol - 2 ]) 487let state . blocktagind = indent ( stopline ) + ( s: curind + s: nextrel ) * shiftwidth () 488return state 489elseif stopline == state . lnum 490" handle special case: previous line (= state.lnum) contains a 491" closing blocktag which is preceded by line-noise; 492" blocktag == "/..." 493let swendtag = match ( tagline , '^\s*</' ) >= 0 494if ! swendtag 495let [ bline , bcol ] = searchpos ( '<' . blocktag [ 1 :] . '\>' , "bnW" ) 496call s: CountITags ( tolower ( getline ( bline )[: bcol - 2 ])) 497let state . baseindent = indent ( bline ) + ( s: curind + s: nextrel ) * shiftwidth () 498return state 499endif 500endif 501endif 502if stopline > stopline2 503let stopline = stopline2 504let stopcol = stopcol2 505endif 506 507" else look back for comment 508let [ comlnum , comcol , found ] = searchpos ( '\(<!--\[\)\|\(<!--\)\|-->' , 'bpnW' , stopline ) 509if found == 2 || found == 3 510" comment opener found, assume a:lnum within comment 511let state . block = ( found == 3 ? 5 : 6 ) 512let state . blocklnr = comlnum 513" check preceding tags in the line: 514call s: CountITags ( tolower ( getline ( comlnum )[: comcol - 2 ])) 515if found == 2 516let state . baseindent = b: hi_indent . baseindent 517endif 518let state . blocktagind = indent ( comlnum ) + ( s: curind + s: nextrel ) * shiftwidth () 519return state 520endif 521 522" else within usual HTML 523let text = tolower ( getline ( state . lnum )) 524 525" Check a:lnum-1 for closing comment (we need indent from the opening line). 526" Not when other tags follow (might be --> inside a string). 527let comcol = stridx ( text , '-->' ) 528if comcol >= 0 && match ( text , '[<>]' , comcol ) <= 0 529call cursor ( state . lnum , comcol + 1 ) 530let [ comlnum , comcol ] = searchpos ( '<!--' , 'bW' ) 531if comlnum == state . lnum 532let text = text [: comcol - 2 ] 533else 534let text = tolower ( getline ( comlnum )[: comcol - 2 ]) 535endif 536call s: CountITags ( text ) 537let state . baseindent = indent ( comlnum ) + ( s: curind + s: nextrel ) * shiftwidth () 538" TODO check tags that follow "-->" 539return state 540endif 541 542" Check if the previous line starts with end tag. 543let swendtag = match ( text , '^\s*</' ) >= 0 544 545" If previous line ended in a closing tag, line up with the opening tag. 546if ! swendtag && text =~ '</' . s: tagname . '\s*>\s*$' 547call cursor ( state . lnum , 99999 ) 548normal ! F< 549let start_lnum = HtmlIndent_FindStartTag () 550if start_lnum > 0 551let state . baseindent = indent ( start_lnum ) 552if col ( '.' ) > 2 553" check for tags before the matching opening tag. 554let text = getline ( start_lnum ) 555let swendtag = match ( text , '^\s*</' ) >= 0 556call s: CountITags ( text [: col ( '.' ) - 2 ]) 557let state . baseindent += s: nextrel * shiftwidth () 558if ! swendtag 559let state . baseindent += s: curind * shiftwidth () 560endif 561endif 562return state 563endif 564endif 565 566" Else: no comments. Skip backwards to find the tag we're inside. 567let [ state . lnum , found ] = HtmlIndent_FindTagStart ( state . lnum ) 568" Check if that line starts with end tag. 569let text = getline ( state . lnum ) 570let swendtag = match ( text , '^\s*</' ) >= 0 571call s: CountITags ( tolower ( text )) 572let state . baseindent = indent ( state . lnum ) + s: nextrel * shiftwidth () 573if ! swendtag 574let state . baseindent += s: curind * shiftwidth () 575endif 576return state 577endfunc "}}} 578 579" Indent inside a <pre> block: Keep indent as-is. 580func s: Alien2 () 581"{{{ 582return -1 583endfunc "}}} 584 585" Return the indent inside a <script> block for javascript. 586func s: Alien3 () 587"{{{ 588let lnum = prevnonblank ( v: lnum - 1 ) 589while lnum > 1 && getline ( lnum ) =~ '^\s*/[/*]' 590" Skip over comments to avoid that cindent() aligns with the <script> tag 591let lnum = prevnonblank ( lnum - 1 ) 592endwhile 593if lnum < b: hi_indent . blocklnr 594" indent for <script> itself 595return b: hi_indent . blocktagind 596endif 597if lnum == b: hi_indent . blocklnr 598" indent for the first line after <script> 599return eval ( b: hi_js1indent ) 600endif 601if b: hi_indent . scripttype == "javascript" 602" indent for further lines 603return GetJavascriptIndent () 604else 605return -1 606endif 607endfunc "}}} 608 609" Return the indent inside a <style> block. 610func s: Alien4 () 611"{{{ 612if prevnonblank ( v: lnum - 1 ) == b: hi_indent . blocklnr 613" indent for first content line 614return eval ( b: hi_css1indent ) 615endif 616return s: CSSIndent () 617endfunc "}}} 618 619" Indending inside a <style> block. Returns the indent. 620func s: CSSIndent () 621"{{{ 622" This handles standard CSS and also Closure stylesheets where special lines 623" start with @. 624" When the line starts with '*' or the previous line starts with "/*" 625" and does not end in "*/", use C indenting to format the comment. 626" Adopted $VIMRUNTIME/indent/css.vim 627let curtext = getline ( v: lnum ) 628if curtext =~ '^\s*[*]' 629 \|| ( v: lnum > 1 && getline ( v: lnum - 1 ) =~ '\s*/\*' 630 \&& getline ( v: lnum - 1 ) !~ '\*/\s*$' ) 631return cindent ( v: lnum ) 632endif 633 634let min_lnum = b: hi_indent . blocklnr 635let prev_lnum = s: CssPrevNonComment ( v: lnum - 1 , min_lnum ) 636let [ prev_lnum , found ] = HtmlIndent_FindTagStart ( prev_lnum ) 637if prev_lnum <= min_lnum 638" Just below the <style> tag, indent for first content line after comments. 639return eval ( b: hi_css1indent ) 640endif 641 642" If the current line starts with "}" align with its match. 643if curtext =~ '^\s*}' 644call cursor ( v: lnum , 1 ) 645try 646normal ! % 647" Found the matching "{", align with it after skipping unfinished lines. 648let align_lnum = s: CssFirstUnfinished ( line ( '.' ), min_lnum ) 649return indent ( align_lnum ) 650catch 651" can't find it, try something else, but it's most likely going to be 652" wrong 653endtry 654endif 655 656" add indent after { 657let brace_counts = HtmlIndent_CountBraces ( prev_lnum ) 658let extra = brace_counts . c_open * shiftwidth () 659 660let prev_text = getline ( prev_lnum ) 661let below_end_brace = prev_text =~ '}\s*$' 662 663" Search back to align with the first line that's unfinished. 664let align_lnum = s: CssFirstUnfinished ( prev_lnum , min_lnum ) 665 666" Handle continuation lines if aligning with previous line and not after a 667" "}". 668if extra == 0 && align_lnum == prev_lnum && ! below_end_brace 669let prev_hasfield = prev_text =~ '^\s*[a-zA-Z0-9-]\+:' 670let prev_special = prev_text =~ '^\s*\(/\*\|@\)' 671if curtext =~ '^\s*\(/\*\|@\)' 672" if the current line is not a comment or starts with @ (used by template 673" systems) reduce indent if previous line is a continuation line 674if ! prev_hasfield && ! prev_special 675let extra = - shiftwidth () 676endif 677else 678let cur_hasfield = curtext =~ '^\s*[a-zA-Z0-9-]\+:' 679let prev_unfinished = s: CssUnfinished ( prev_text ) 680if prev_unfinished 681" Continuation line has extra indent if the previous line was not a 682" continuation line. 683let extra = shiftwidth () 684" Align with @if 685if prev_text =~ '^\s*@if ' 686let extra = 4 687endif 688elseif cur_hasfield && ! prev_hasfield && ! prev_special 689" less indent below a continuation line 690let extra = - shiftwidth () 691endif 692endif 693endif 694 695if below_end_brace 696" find matching {, if that line starts with @ it's not the start of a rule 697" but something else from a template system 698call cursor ( prev_lnum , 1 ) 699call search ( '}\s*$' ) 700try 701normal ! % 702" Found the matching "{", align with it. 703let align_lnum = s: CssFirstUnfinished ( line ( '.' ), min_lnum ) 704let special = getline ( align_lnum ) =~ '^\s*@' 705catch 706let special = 0 707endtry 708if special 709" do not reduce indent below @{ ... } 710if extra < 0 711let extra += shiftwidth () 712endif 713else 714let extra -= ( brace_counts . c_close - ( prev_text =~ '^\s*}' )) * shiftwidth () 715endif 716endif 717 718" if no extra indent yet... 719if extra == 0 720if brace_counts . p_open > brace_counts . p_close 721" previous line has more ( than ): add a shiftwidth 722let extra = shiftwidth () 723elseif brace_counts . p_open < brace_counts . p_close 724" previous line has more ) than (: subtract a shiftwidth 725let extra = - shiftwidth () 726endif 727endif 728 729return indent ( align_lnum ) + extra 730endfunc "}}} 731 732" Inside <style>: Whether a line is unfinished. 733" tag: 734" tag: blah 735" tag: blah && 736" tag: blah || 737func s: CssUnfinished ( text ) 738"{{{ 739return a: text =~ '\(||\|&&\|:\|\k\)\s*$' 740endfunc "}}} 741 742" Search back for the first unfinished line above "lnum". 743func s: CssFirstUnfinished ( lnum , min_lnum ) 744"{{{ 745let align_lnum = a: lnum 746while align_lnum > a: min_lnum && s: CssUnfinished ( getline ( align_lnum - 1 )) 747let align_lnum -= 1 748endwhile 749return align_lnum 750endfunc "}}} 751 752" Find the non-empty line at or before "lnum" that is not a comment. 753func s: CssPrevNonComment ( lnum , stopline ) 754"{{{ 755" caller starts from a line a:lnum + 1 that is not a comment 756let lnum = prevnonblank ( a: lnum ) 757while 1 758let ccol = match ( getline ( lnum ), '\*/' ) 759if ccol < 0 760" No comment end thus it's something else. 761return lnum 762endif 763call cursor ( lnum , ccol + 1 ) 764" Search back for the /* that starts the comment 765let lnum = search ( '/\*' , 'bW' , a: stopline ) 766if indent ( "." ) == virtcol ( "." ) - 1 767" The found /* is at the start of the line. Now go back to the line 768" above it and again check if it is a comment. 769let lnum = prevnonblank ( lnum - 1 ) 770else 771" /* is after something else, thus it's not a comment line. 772return lnum 773endif 774endwhile 775endfunc "}}} 776 777" Check the number of {} and () in line "lnum". Return a dict with the counts. 778func HtmlIndent_CountBraces ( lnum ) 779"{{{ 780let brs = substitute ( getline ( a: lnum ), '[''"].\{-}[''"]\|/\*.\{-}\*/\|/\*.*$\|[^{}()]' , '' , 'g' ) 781let c_open = 0 782let c_close = 0 783let p_open = 0 784let p_close = 0 785for brace in split ( brs , '\zs' ) 786if brace == "{" 787let c_open += 1 788elseif brace == "}" 789if c_open > 0 790let c_open -= 1 791else 792let c_close += 1 793endif 794elseif brace == '(' 795let p_open += 1 796elseif brace == ')' 797if p_open > 0 798let p_open -= 1 799else 800let p_close += 1 801endif 802endif 803endfor 804return { 'c_open' : c_open , 805 \'c_close' : c_close , 806 \'p_open' : p_open , 807 \'p_close' : p_close } 808endfunc "}}} 809 810" Return the indent for a comment: <!-- --> 811func s: Alien5 () 812"{{{ 813let curtext = getline ( v: lnum ) 814if curtext =~ '^\s*\zs-->' 815" current line starts with end of comment, line up with comment start. 816call cursor ( v: lnum , 0 ) 817let lnum = search ( '<!--' , 'b' ) 818if lnum > 0 819" TODO: what if <!-- is not at the start of the line? 820return indent ( lnum ) 821endif 822 823" Strange, can't find it. 824return -1 825endif 826 827let prevlnum = prevnonblank ( v: lnum - 1 ) 828let prevtext = getline ( prevlnum ) 829let idx = match ( prevtext , '^\s*\zs<!--' ) 830if idx >= 0 831" just below comment start, add a shiftwidth 832return indent ( prevlnum ) + shiftwidth () 833endif 834 835" Some files add 4 spaces just below a TODO line. It's difficult to detect 836" the end of the TODO, so let's not do that. 837 838" Align with the previous non-blank line. 839return indent ( prevlnum ) 840endfunc "}}} 841 842" Return the indent for conditional comment: <!--[ ![endif]--> 843func s: Alien6 () 844"{{{ 845let curtext = getline ( v: lnum ) 846if curtext =~ '\s*\zs<!\[endif\]-->' 847" current line starts with end of comment, line up with comment start. 848let lnum = search ( '<!--' , 'bn' ) 849if lnum > 0 850return indent ( lnum ) 851endif 852endif 853return b: hi_indent . baseindent + shiftwidth () 854endfunc "}}} 855 856" When the "lnum" line ends in ">" find the line containing the matching "<". 857func HtmlIndent_FindTagStart ( lnum ) 858"{{{ 859" Avoids using the indent of a continuation line. 860" Moves the cursor. 861" Return two values: 862" - the matching line number or "lnum". 863" - a flag indicating whether we found the end of a tag. 864" This method is global so that HTML-like indenters can use it. 865" To avoid matching " > " or " < " inside a string require that the opening 866" "<" is followed by a word character and the closing ">" comes after a 867" non-white character. 868let idx = match ( getline ( a: lnum ), '\S>\s*$' ) 869if idx > 0 870call cursor ( a: lnum , idx ) 871" VIM_INDENT_TEST_TRACE_START 872let lnum = searchpair ( '<\w' , '' , '\S>' , 'bW' , '' , max ([ a: lnum - b: html_indent_line_limit , 0 ])) 873" VIM_INDENT_TEST_TRACE_END HtmlIndent_FindTagStart 874if lnum > 0 875return [ lnum , 1 ] 876endif 877endif 878return [ a: lnum , 0 ] 879endfunc "}}} 880 881" Find the unclosed start tag from the current cursor position. 882func HtmlIndent_FindStartTag () 883"{{{ 884" The cursor must be on or before a closing tag. 885" If found, positions the cursor at the match and returns the line number. 886" Otherwise returns 0. 887let tagname = matchstr ( getline ( '.' )[ col ( '.' ) - 1 :], '</\zs' . s: tagname . '\ze' ) 888let start_lnum = searchpair ( '<' . tagname . '\>' , '' , '</' . tagname . '\>' , 'bW' ) 889if start_lnum > 0 890return start_lnum 891endif 892return 0 893endfunc "}}} 894 895" Moves the cursor from a "<" to the matching ">". 896func HtmlIndent_FindTagEnd () 897"{{{ 898" Call this with the cursor on the "<" of a start tag. 899" This will move the cursor to the ">" of the matching end tag or, when it's 900" a self-closing tag, to the matching ">". 901" Limited to look up to b:html_indent_line_limit lines away. 902let text = getline ( '.' ) 903let tagname = matchstr ( text , s: tagname . '\|!--' , col ( '.' )) 904if tagname == '!--' 905call search ( '--\zs>' ) 906elseif s: get_tag ( '/' . tagname ) != 0 907" tag with a closing tag, find matching "</tag>" 908" VIM_INDENT_TEST_TRACE_START 909call searchpair ( '<' . tagname , '' , '</' . tagname . '\zs>' , 'W' , '' , line ( '.' ) + b: html_indent_line_limit ) 910" VIM_INDENT_TEST_TRACE_END HtmlIndent_FindTagEnd 911else 912" self-closing tag, find the ">" 913call search ( '\S\zs>' ) 914endif 915endfunc "}}} 916 917" Indenting inside a start tag. Return the correct indent or -1 if unknown. 918func s: InsideTag ( foundHtmlString ) 919"{{{ 920if a: foundHtmlString 921" Inside an attribute string. 922" Align with the opening quote or use an external function. 923let lnum = v: lnum - 1 924if lnum > 1 925if exists ( 'b:html_indent_tag_string_func' ) 926return b: html_indent_tag_string_func ( lnum ) 927endif 928" If there is a double quote in the previous line, indent with the 929" character after it. 930if getline ( lnum ) =~ '"' 931call cursor ( lnum , 0 ) 932normal f" 933return virtcol ( '.' ) 934endif 935return indent ( lnum ) 936endif 937endif 938 939" Should be another attribute: " attr="val". Align with the previous 940" attribute start. 941let lnum = v: lnum 942while lnum > 1 943let lnum -= 1 944let text = getline ( lnum ) 945" Find a match with one of these, align with "attr": 946" attr= 947" <tag attr= 948" text<tag attr= 949" <tag>text</tag>text<tag attr= 950" For long lines search for the first match, finding the last match 951" gets very slow. 952if len ( text ) < 300 953let idx = match ( text , '.*\s\zs[_a-zA-Z0-9-]\+="' ) 954else 955let idx = match ( text , '\s\zs[_a-zA-Z0-9-]\+="' ) 956endif 957if idx == -1 958" try <tag attr 959let idx = match ( text , '<' . s: tagname . '\s\+\zs\w' ) 960endif 961if idx == -1 962" after just "<tag" indent two levels more by default 963let idx = match ( text , '<' . s: tagname . '$' ) 964if idx >= 0 965call cursor ( lnum , idx + 1 ) 966return virtcol ( '.' ) - 1 + shiftwidth () * b: hi_attr_indent 967endif 968endif 969if idx > 0 970" Found the attribute to align with. 971call cursor ( lnum , idx ) 972return virtcol ( '.' ) 973endif 974endwhile 975return -1 976endfunc "}}} 977 978" THE MAIN INDENT FUNCTION. Return the amount of indent for v:lnum. 979func HtmlIndent () 980"{{{ 981if prevnonblank ( v: lnum - 1 ) < 1 982" First non-blank line has no indent. 983return 0 984endif 985 986let curtext = tolower ( getline ( v: lnum )) 987let indentunit = shiftwidth () 988 989let b: hi_newstate = {} 990let b: hi_newstate . lnum = v: lnum 991 992" When syntax HL is enabled, detect we are inside a tag. Indenting inside 993" a tag works very differently. Do not do this when the line starts with 994" "<", it gets the "htmlTag" ID but we are not inside a tag then. 995if curtext !~ '^\s*<' 996normal ! ^ 997let stack = synstack ( v: lnum , col ( '.' )) " assumes there are no tabs 998let foundHtmlString = 0 999for synid in reverse ( stack ) 1000let name = synIDattr ( synid , "name" ) 1001if index ( b: hi_insideStringNames , name ) >= 0 1002let foundHtmlString = 1 1003elseif index ( b: hi_insideTagNames , name ) >= 0 1004" Yes, we are inside a tag. 1005let indent = s: InsideTag ( foundHtmlString ) 1006if indent >= 0 1007" Do not keep the state. TODO: could keep the block type. 1008let b: hi_indent . lnum = 0 1009return indent 1010endif 1011endif 1012endfor 1013endif 1014 1015" does the line start with a closing tag? 1016let swendtag = match ( curtext , '^\s*</' ) >= 0 1017 1018if prevnonblank ( v: lnum - 1 ) == b: hi_indent . lnum && b: hi_lasttick == b: changedtick - 1 1019" use state (continue from previous line) 1020else 1021" start over (know nothing) 1022let b: hi_indent = s: FreshState ( v: lnum ) 1023endif 1024 1025if b: hi_indent . block >= 2 1026" within block 1027let endtag = s: endtags [ b: hi_indent . block ] 1028let blockend = stridx ( curtext , endtag ) 1029if blockend >= 0 1030" block ends here 1031let b: hi_newstate . block = 0 1032" calc indent for REST OF LINE (may start more blocks): 1033call s: CountTagsAndState ( strpart ( curtext , blockend + strlen ( endtag ))) 1034if swendtag && b: hi_indent . block != 5 1035let indent = b: hi_indent . blocktagind + s: curind * indentunit 1036let b: hi_newstate . baseindent = indent + s: nextrel * indentunit 1037else 1038let indent = s: Alien { b: hi_indent . block }() 1039let b: hi_newstate . baseindent = b: hi_indent . blocktagind + s: nextrel * indentunit 1040endif 1041else 1042" block continues 1043" indent this line with alien method 1044let indent = s: Alien { b: hi_indent . block }() 1045endif 1046else 1047" not within a block - within usual html 1048let b: hi_newstate . block = b: hi_indent . block 1049if swendtag 1050" The current line starts with an end tag, align with its start tag. 1051call cursor ( v: lnum , 1 ) 1052let start_lnum = HtmlIndent_FindStartTag () 1053if start_lnum > 0 1054" check for the line starting with something inside a tag: 1055" <sometag <- align here 1056" attr=val><open> not here 1057let text = getline ( start_lnum ) 1058let angle = matchstr ( text , '[<>]' ) 1059if angle == '>' 1060call cursor ( start_lnum , 1 ) 1061normal ! f>% 1062let start_lnum = line ( '.' ) 1063let text = getline ( start_lnum ) 1064endif 1065 1066let indent = indent ( start_lnum ) 1067if col ( '.' ) > 2 1068let swendtag = match ( text , '^\s*</' ) >= 0 1069call s: CountITags ( text [: col ( '.' ) - 2 ]) 1070let indent += s: nextrel * shiftwidth () 1071if ! swendtag 1072let indent += s: curind * shiftwidth () 1073endif 1074endif 1075else 1076" not sure what to do 1077let indent = b: hi_indent . baseindent 1078endif 1079let b: hi_newstate . baseindent = indent 1080else 1081call s: CountTagsAndState ( curtext ) 1082let indent = b: hi_indent . baseindent 1083let b: hi_newstate . baseindent = indent + ( s: curind + s: nextrel ) * indentunit 1084endif 1085endif 1086 1087let b: hi_lasttick = b: changedtick 1088call extend ( b: hi_indent , b: hi_newstate , "force" ) 1089return indent 1090endfunc "}}} 1091 1092" Check user settings when loading this script the first time. 1093call HtmlIndent_CheckUserSettings () 1094 1095let & cpo = s: cpo_save 1096unlet s: cpo_save 1097 1098" vim: fdm=marker ts=8 sw=2 tw=78