1 " Vim indent script for HTML
3 " Maintainer: Bram Moolenaar
4 " Original Author: Andy Wokula <anwoku@yahoo.de>
5 " Last Change: 2017 Jan 17
7 " Description: HTML indent script with cached state for faster indenting on a
9 " Supports template systems through hooks.
10 " Supports Closure stylesheets.
13 " indent/html.vim (2006 Jun 05) from J. Zellner
14 " indent/css.vim (2006 Dec 20) from N. Weibull
17 " 2014 June (v1.0) overhaul (Bram)
18 " 2012 Oct 21 (v0.9) added support for shiftwidth()
19 " 2011 Sep 09 (v0.8) added HTML5 tags (thx to J. Zuckerman)
20 " 2008 Apr 28 (v0.6) revised customization
21 " 2008 Mar 09 (v0.5) fixed 'indk' issue (thx to C.J. Robinson)
24 " Init Folklore, check user settings (2nd time ++)
25 if exists("b:did_indent") "{{{
29 " Load the Javascript indent script first, it defines GetJavascriptIndent().
31 " Load base python indent.
32 if !exists('*GetJavascriptIndent')
33 runtime! indent/javascript.vim
37 setlocal indentexpr=HtmlIndent()
38 setlocal indentkeys=o,O,<Return>,<>>,{,},!^F
40 " Needed for % to work when finding start/end of a tag.
41 setlocal matchpairs+=<:>
43 let b:undo_indent = "setlocal inde< indk<"
45 " b:hi_indent keeps state to speed up indenting consecutive lines.
46 let b:hi_indent = {"lnum": -1}
48 """""" Code below this is loaded only once. """""
49 if exists("*HtmlIndent") && !exists('g:force_reload_html')
50 call HtmlIndent_CheckUserSettings()
54 " shiftwidth() exists since patch 7.3.694
55 if exists('*shiftwidth')
56 let s:ShiftWidth = function('shiftwidth')
63 " Allow for line continuation below.
68 " Check and process settings from b:html_indent and g:html_indent... variables.
69 " Prefer using buffer-local settings over global settings, so that there can
70 " be defaults for all HTML files and exceptions for specific types of HTML
72 func! HtmlIndent_CheckUserSettings()
75 if exists("b:html_indent_inctags")
76 let inctags = b:html_indent_inctags
77 elseif exists("g:html_indent_inctags")
78 let inctags = g:html_indent_inctags
82 call s:AddITags(b:hi_tags, split(inctags, ","))
86 if exists("b:html_indent_autotags")
87 let autotags = b:html_indent_autotags
88 elseif exists("g:html_indent_autotags")
89 let autotags = g:html_indent_autotags
91 let b:hi_removed_tags = {}
93 call s:RemoveITags(b:hi_removed_tags, split(autotags, ","))
96 " Syntax names indicating being inside a string of an attribute value.
98 if exists("b:html_indent_string_names")
99 let string_names = b:html_indent_string_names
100 elseif exists("g:html_indent_string_names")
101 let string_names = g:html_indent_string_names
103 let b:hi_insideStringNames = ['htmlString']
104 if len(string_names) > 0
105 for s in string_names
106 call add(b:hi_insideStringNames, s)
110 " Syntax names indicating being inside a tag.
112 if exists("b:html_indent_tag_names")
113 let tag_names = b:html_indent_tag_names
114 elseif exists("g:html_indent_tag_names")
115 let tag_names = g:html_indent_tag_names
117 let b:hi_insideTagNames = ['htmlTag', 'htmlScriptTag']
118 if len(tag_names) > 0
120 call add(b:hi_insideTagNames, s)
124 let indone = {"zero": 0
125 \,"auto": "indent(prevnonblank(v:lnum-1))"
126 \,"inc": "b:hi_indent.blocktagind + s:ShiftWidth()"}
129 if exists("b:html_indent_script1")
130 let script1 = b:html_indent_script1
131 elseif exists("g:html_indent_script1")
132 let script1 = g:html_indent_script1
135 let b:hi_js1indent = get(indone, script1, indone.zero)
137 let b:hi_js1indent = 0
141 if exists("b:html_indent_style1")
142 let style1 = b:html_indent_style1
143 elseif exists("g:html_indent_style1")
144 let style1 = g:html_indent_style1
147 let b:hi_css1indent = get(indone, style1, indone.zero)
149 let b:hi_css1indent = 0
152 if !exists('b:html_indent_line_limit')
153 if exists('g:html_indent_line_limit')
154 let b:html_indent_line_limit = g:html_indent_line_limit
156 let b:html_indent_line_limit = 200
163 let b:hi_lasttick = 0
164 let b:hi_newstate = {}
168 " Fill the s:indent_tags dict with known tags.
169 " The key is "tagname" or "/tagname". {{{
176 " 6 conditional comment start
182 " -6 conditional comment end
183 let s:indent_tags = {}
184 let s:endtags = [0,0,0,0,0,0,0] " long enough for the highest index
187 " Add a list of tag names for a pair of <tag> </tag> to "tags".
188 func! s:AddITags(tags, taglist)
190 for itag in a:taglist
192 let a:tags['/' . itag] = -1
196 " Take a list of tag name pairs that are not to be used as tag pairs.
197 func! s:RemoveITags(tags, taglist)
199 for itag in a:taglist
201 let a:tags['/' . itag] = 1
205 " Add a block tag, that is a tag with a different kind of indenting.
206 func! s:AddBlockTag(tag, id, ...)
208 if !(a:id >= 2 && a:id < len(s:endtags))
209 echoerr 'AddBlockTag ' . a:id
212 let s:indent_tags[a:tag] = a:id
214 let s:indent_tags['/' . a:tag] = -a:id
215 let s:endtags[a:id] = "</" . a:tag . ">"
217 let s:indent_tags[a:1] = -a:id
218 let s:endtags[a:id] = a:1
222 " Add known tag pairs.
223 " Self-closing tags and tags that are sometimes {{{
224 " self-closing (e.g., <p>) are not here (when encountering </p> we can find
225 " the matching <p>, but not the other way around).
227 call s:AddITags(s:indent_tags, [
228 \ 'a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big',
229 \ 'blockquote', 'body', 'button', 'caption', 'center', 'cite', 'code',
230 \ 'colgroup', 'del', 'dfn', 'dir', 'div', 'dl', 'em', 'fieldset', 'font',
231 \ 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'html',
232 \ 'i', 'iframe', 'ins', 'kbd', 'label', 'legend', 'li',
233 \ 'map', 'menu', 'noframes', 'noscript', 'object', 'ol',
234 \ 'optgroup', 'q', 's', 'samp', 'select', 'small', 'span', 'strong', 'sub',
235 \ 'sup', 'table', 'textarea', 'title', 'tt', 'u', 'ul', 'var', 'th', 'td',
236 \ 'tr', 'tbody', 'tfoot', 'thead'])
238 " New HTML5 elements:
239 call s:AddITags(s:indent_tags, [
240 \ 'area', 'article', 'aside', 'audio', 'bdi', 'canvas',
241 \ 'command', 'data', 'datalist', 'details', 'embed', 'figcaption',
242 \ 'figure', 'footer', 'header', 'keygen', 'mark', 'meter', 'nav', 'output',
243 \ 'progress', 'rp', 'rt', 'ruby', 'section', 'source', 'summary', 'svg',
244 \ 'time', 'track', 'video', 'wbr'])
246 " Tags added for web components:
247 call s:AddITags(s:indent_tags, [
248 \ 'content', 'shadow', 'template'])
251 " Add Block Tags: these contain alien content
253 call s:AddBlockTag('pre', 2)
254 call s:AddBlockTag('script', 3)
255 call s:AddBlockTag('style', 4)
256 call s:AddBlockTag('<!--', 5, '-->')
257 call s:AddBlockTag('<!--[', 6, '![endif]-->')
260 " Return non-zero when "tagname" is an opening tag, not being a block tag, for
261 " which there should be a closing tag. Can be used by scripts that include
263 func! HtmlIndent_IsOpenTag(tagname)
265 if get(s:indent_tags, a:tagname) == 1
268 return get(b:hi_tags, a:tagname) == 1
271 " Get the value for "tagname", taking care of buffer-local tags.
272 func! s:get_tag(tagname)
274 let i = get(s:indent_tags, a:tagname)
275 if (i == 1 || i == -1) && get(b:hi_removed_tags, a:tagname) != 0
279 let i = get(b:hi_tags, a:tagname)
284 " Count the number of start and end tags in "text".
285 func! s:CountITags(text)
287 " Store the result in s:curind and s:nextrel.
288 let s:curind = 0 " relative indent steps for current line [unit &sw]:
289 let s:nextrel = 0 " relative indent steps for next line [unit &sw]:
290 let s:block = 0 " assume starting outside of a block
291 let s:countonly = 1 " don't change state
292 call substitute(a:text, '<\zs/\=\w\+\(-\w\+\)*\>\|<!--\[\|\[endif\]-->\|<!--\|-->', '\=s:CheckTag(submatch(0))', 'g')
296 " Count the number of start and end tags in text.
297 func! s:CountTagsAndState(text)
299 " Store the result in s:curind and s:nextrel. Update b:hi_newstate.block.
300 let s:curind = 0 " relative indent steps for current line [unit &sw]:
301 let s:nextrel = 0 " relative indent steps for next line [unit &sw]:
303 let s:block = b:hi_newstate.block
304 let tmp = substitute(a:text, '<\zs/\=\w\+\(-\w\+\)*\>\|<!--\[\|\[endif\]-->\|<!--\|-->', '\=s:CheckTag(submatch(0))', 'g')
306 let b:hi_newstate.scripttype = s:GetScriptType(matchstr(tmp, '\C.*<SCRIPT\>\zs[^>]*'))
308 let b:hi_newstate.block = s:block
311 " Used by s:CountITags() and s:CountTagsAndState().
312 func! s:CheckTag(itag)
314 " Returns an empty string or "SCRIPT".
315 " a:itag can be "tag" or "/tag" or "<!--" or "-->"
316 if (s:CheckCustomTag(a:itag))
319 let ind = s:get_tag(a:itag)
323 " ignore itag within a block
338 " block-tag (opening or closing)
339 return s:CheckBlockTag(a:itag, ind)
340 " else ind==0 (other tag found): keep indent
345 " Used by s:CheckTag(). Returns an empty string or "SCRIPT".
346 func! s:CheckBlockTag(blocktag, ind)
349 " a block starts here
351 " already in a block (nesting) - ignore
352 " especially ignore comments after other blocktags
355 let s:block = a:ind " block type
359 let b:hi_newstate.blocklnr = v:lnum
360 " save allover indent for the endtag
361 let b:hi_newstate.blocktagind = b:hi_indent.baseindent + (s:nextrel + s:curind) * s:ShiftWidth()
363 return "SCRIPT" " all except this must be lowercase
364 " line is to be checked again for the type attribute
368 " we get here if starting and closing a block-tag on the same line
373 " Used by s:CheckTag().
374 func! s:CheckCustomTag(ctag)
376 " Returns 1 if ctag is the tag for a custom element, 0 otherwise.
377 " a:ctag can be "tag" or "/tag" or "<!--" or "-->"
378 let pattern = '\%\(\w\+-\)\+\w\+'
379 if match(a:ctag, pattern) == -1
382 if matchstr(a:ctag, '\/\ze.\+') == "/"
385 " ignore ctag within a block
403 " Return the <script> type: either "javascript" or ""
404 func! s:GetScriptType(str)
406 if a:str == "" || a:str =~ "java"
413 " Look back in the file, starting at a:lnum - 1, to compute a state for the
414 " start of line a:lnum. Return the new state.
415 func! s:FreshState(lnum)
417 " A state is to know ALL relevant details about the
418 " lines 1..a:lnum-1, initial calculating (here!) can be slow, but updating is
419 " fast (incremental).
420 " TODO: this should be split up in detecting the block type and computing the
421 " indent for the block type, so that when we do not know the indent we do
422 " not need to clear the whole state and re-detect the block type again.
424 " lnum last indented line == prevnonblank(a:lnum - 1)
425 " block = 0 a:lnum located within special tag: 0:none, 2:<pre>,
426 " 3:<script>, 4:<style>, 5:<!--, 6:<!--[
427 " baseindent use this indent for line a:lnum as a start - kind of
428 " autoindent (if block==0)
429 " scripttype = '' type attribute of a script tag (if block==3)
430 " blocktagind indent for current opening (get) and closing (set)
431 " blocktag (if block!=0)
432 " blocklnr lnum of starting blocktag (if block!=0)
433 " inattr line {lnum} starts with attributes of a tag
435 let state.lnum = prevnonblank(a:lnum - 1)
436 let state.scripttype = ""
437 let state.blocktagind = -1
439 let state.baseindent = 0
440 let state.blocklnr = 0
448 " remember startline state.lnum
449 " look back for <pre, </pre, <script, </script, <style, </style tags
451 " if opening tag found,
452 " assume a:lnum within block
454 " look back in result range (stopline, startline) for comment
455 " \ delimiters (<!--, -->)
456 " if comment opener found,
457 " assume a:lnum within comment
459 " assume usual html for a:lnum
460 " if a:lnum-1 has a closing comment
461 " look back to get indent of comment opener
464 " look back for a blocktag
465 let stopline2 = v:lnum + 1
466 if has_key(b:hi_indent, 'block') && b:hi_indent.block > 5
467 let [stopline2, stopcol2] = searchpos('<!--', 'bnW')
469 let [stopline, stopcol] = searchpos('\c<\zs\/\=\%(pre\>\|script\>\|style\>\)', "bnW")
470 if stopline > 0 && stopline < stopline2
471 " ugly ... why isn't there searchstr()
472 let tagline = tolower(getline(stopline))
473 let blocktag = matchstr(tagline, '\/\=\%(pre\>\|script\>\|style\>\)', stopcol - 1)
474 if blocktag[0] != "/"
475 " opening tag found, assume a:lnum within block
476 let state.block = s:indent_tags[blocktag]
478 let state.scripttype = s:GetScriptType(matchstr(tagline, '\>[^>]*', stopcol))
480 let state.blocklnr = stopline
481 " check preceding tags in the line:
482 call s:CountITags(tagline[: stopcol-2])
483 let state.blocktagind = indent(stopline) + (s:curind + s:nextrel) * s:ShiftWidth()
485 elseif stopline == state.lnum
486 " handle special case: previous line (= state.lnum) contains a
487 " closing blocktag which is preceded by line-noise;
489 let swendtag = match(tagline, '^\s*</') >= 0
491 let [bline, bcol] = searchpos('<'.blocktag[1:].'\>', "bnW")
492 call s:CountITags(tolower(getline(bline)[: bcol-2]))
493 let state.baseindent = indent(bline) + (s:curind + s:nextrel) * s:ShiftWidth()
498 if stopline > stopline2
499 let stopline = stopline2
500 let stopcol = stopcol2
503 " else look back for comment
504 let [comlnum, comcol, found] = searchpos('\(<!--\[\)\|\(<!--\)\|-->', 'bpnW', stopline)
505 if found == 2 || found == 3
506 " comment opener found, assume a:lnum within comment
507 let state.block = (found == 3 ? 5 : 6)
508 let state.blocklnr = comlnum
509 " check preceding tags in the line:
510 call s:CountITags(tolower(getline(comlnum)[: comcol-2]))
512 let state.baseindent = b:hi_indent.baseindent
514 let state.blocktagind = indent(comlnum) + (s:curind + s:nextrel) * s:ShiftWidth()
518 " else within usual HTML
519 let text = tolower(getline(state.lnum))
521 " Check a:lnum-1 for closing comment (we need indent from the opening line).
522 " Not when other tags follow (might be --> inside a string).
523 let comcol = stridx(text, '-->')
524 if comcol >= 0 && match(text, '[<>]', comcol) <= 0
525 call cursor(state.lnum, comcol + 1)
526 let [comlnum, comcol] = searchpos('<!--', 'bW')
527 if comlnum == state.lnum
528 let text = text[: comcol-2]
530 let text = tolower(getline(comlnum)[: comcol-2])
532 call s:CountITags(text)
533 let state.baseindent = indent(comlnum) + (s:curind + s:nextrel) * s:ShiftWidth()
534 " TODO check tags that follow "-->"
538 " Check if the previous line starts with end tag.
539 let swendtag = match(text, '^\s*</') >= 0
541 " If previous line ended in a closing tag, line up with the opening tag.
542 if !swendtag && text =~ '</\w\+\s*>\s*$'
543 call cursor(state.lnum, 99999)
545 let start_lnum = HtmlIndent_FindStartTag()
547 let state.baseindent = indent(start_lnum)
549 " check for tags before the matching opening tag.
550 let text = getline(start_lnum)
551 let swendtag = match(text, '^\s*</') >= 0
552 call s:CountITags(text[: col('.') - 2])
553 let state.baseindent += s:nextrel * s:ShiftWidth()
555 let state.baseindent += s:curind * s:ShiftWidth()
562 " Else: no comments. Skip backwards to find the tag we're inside.
563 let [state.lnum, found] = HtmlIndent_FindTagStart(state.lnum)
564 " Check if that line starts with end tag.
565 let text = getline(state.lnum)
566 let swendtag = match(text, '^\s*</') >= 0
567 call s:CountITags(tolower(text))
568 let state.baseindent = indent(state.lnum) + s:nextrel * s:ShiftWidth()
570 let state.baseindent += s:curind * s:ShiftWidth()
575 " Indent inside a <pre> block: Keep indent as-is.
581 " Return the indent inside a <script> block for javascript.
584 let lnum = prevnonblank(v:lnum - 1)
585 while lnum > 1 && getline(lnum) =~ '^\s*/[/*]'
586 " Skip over comments to avoid that cindent() aligns with the <script> tag
587 let lnum = prevnonblank(lnum - 1)
589 if lnum == b:hi_indent.blocklnr
590 " indent for the first line after <script>
591 return eval(b:hi_js1indent)
593 if b:hi_indent.scripttype == "javascript"
594 return GetJavascriptIndent()
600 " Return the indent inside a <style> block.
603 if prevnonblank(v:lnum-1) == b:hi_indent.blocklnr
604 " indent for first content line
605 return eval(b:hi_css1indent)
610 " Indending inside a <style> block. Returns the indent.
613 " This handles standard CSS and also Closure stylesheets where special lines
615 " When the line starts with '*' or the previous line starts with "/*"
616 " and does not end in "*/", use C indenting to format the comment.
617 " Adopted $VIMRUNTIME/indent/css.vim
618 let curtext = getline(v:lnum)
619 if curtext =~ '^\s*[*]'
620 \ || (v:lnum > 1 && getline(v:lnum - 1) =~ '\s*/\*'
621 \ && getline(v:lnum - 1) !~ '\*/\s*$')
622 return cindent(v:lnum)
625 let min_lnum = b:hi_indent.blocklnr
626 let prev_lnum = s:CssPrevNonComment(v:lnum - 1, min_lnum)
627 let [prev_lnum, found] = HtmlIndent_FindTagStart(prev_lnum)
628 if prev_lnum <= min_lnum
629 " Just below the <style> tag, indent for first content line after comments.
630 return eval(b:hi_css1indent)
633 " If the current line starts with "}" align with it's match.
634 if curtext =~ '^\s*}'
635 call cursor(v:lnum, 1)
638 " Found the matching "{", align with it after skipping unfinished lines.
639 let align_lnum = s:CssFirstUnfinished(line('.'), min_lnum)
640 return indent(align_lnum)
642 " can't find it, try something else, but it's most likely going to be
648 let brace_counts = HtmlIndent_CountBraces(prev_lnum)
649 let extra = brace_counts.c_open * s:ShiftWidth()
651 let prev_text = getline(prev_lnum)
652 let below_end_brace = prev_text =~ '}\s*$'
654 " Search back to align with the first line that's unfinished.
655 let align_lnum = s:CssFirstUnfinished(prev_lnum, min_lnum)
657 " Handle continuation lines if aligning with previous line and not after a
659 if extra == 0 && align_lnum == prev_lnum && !below_end_brace
660 let prev_hasfield = prev_text =~ '^\s*[a-zA-Z0-9-]\+:'
661 let prev_special = prev_text =~ '^\s*\(/\*\|@\)'
662 if curtext =~ '^\s*\(/\*\|@\)'
663 " if the current line is not a comment or starts with @ (used by template
664 " systems) reduce indent if previous line is a continuation line
665 if !prev_hasfield && !prev_special
666 let extra = -s:ShiftWidth()
669 let cur_hasfield = curtext =~ '^\s*[a-zA-Z0-9-]\+:'
670 let prev_unfinished = s:CssUnfinished(prev_text)
671 if !cur_hasfield && (prev_hasfield || prev_unfinished)
672 " Continuation line has extra indent if the previous line was not a
674 let extra = s:ShiftWidth()
676 if prev_text =~ '^\s*@if '
679 elseif cur_hasfield && !prev_hasfield && !prev_special
680 " less indent below a continuation line
681 let extra = -s:ShiftWidth()
687 " find matching {, if that line starts with @ it's not the start of a rule
688 " but something else from a template system
689 call cursor(prev_lnum, 1)
693 " Found the matching "{", align with it.
694 let align_lnum = s:CssFirstUnfinished(line('.'), min_lnum)
695 let special = getline(align_lnum) =~ '^\s*@'
700 " do not reduce indent below @{ ... }
702 let extra += s:ShiftWidth()
705 let extra -= (brace_counts.c_close - (prev_text =~ '^\s*}')) * s:ShiftWidth()
709 " if no extra indent yet...
711 if brace_counts.p_open > brace_counts.p_close
712 " previous line has more ( than ): add a shiftwidth
713 let extra = s:ShiftWidth()
714 elseif brace_counts.p_open < brace_counts.p_close
715 " previous line has more ) than (: subtract a shiftwidth
716 let extra = -s:ShiftWidth()
720 return indent(align_lnum) + extra
723 " Inside <style>: Whether a line is unfinished.
724 func! s:CssUnfinished(text)
726 return a:text =~ '\s\(||\|&&\|:\)\s*$'
729 " Search back for the first unfinished line above "lnum".
730 func! s:CssFirstUnfinished(lnum, min_lnum)
732 let align_lnum = a:lnum
733 while align_lnum > a:min_lnum && s:CssUnfinished(getline(align_lnum - 1))
739 " Find the non-empty line at or before "lnum" that is not a comment.
740 func! s:CssPrevNonComment(lnum, stopline)
742 " caller starts from a line a:lnum + 1 that is not a comment
743 let lnum = prevnonblank(a:lnum)
745 let ccol = match(getline(lnum), '\*/')
747 " No comment end thus it's something else.
750 call cursor(lnum, ccol + 1)
751 " Search back for the /* that starts the comment
752 let lnum = search('/\*', 'bW', a:stopline)
753 if indent(".") == virtcol(".") - 1
754 " The found /* is at the start of the line. Now go back to the line
755 " above it and again check if it is a comment.
756 let lnum = prevnonblank(lnum - 1)
758 " /* is after something else, thus it's not a comment line.
764 " Check the number of {} and () in line "lnum". Return a dict with the counts.
765 func! HtmlIndent_CountBraces(lnum)
767 let brs = substitute(getline(a:lnum), '[''"].\{-}[''"]\|/\*.\{-}\*/\|/\*.*$\|[^{}()]', '', 'g')
772 for brace in split(brs, '\zs')
791 return {'c_open': c_open,
792 \ 'c_close': c_close,
794 \ 'p_close': p_close}
797 " Return the indent for a comment: <!-- -->
800 let curtext = getline(v:lnum)
801 if curtext =~ '^\s*\zs-->'
802 " current line starts with end of comment, line up with comment start.
803 call cursor(v:lnum, 0)
804 let lnum = search('<!--', 'b')
806 " TODO: what if <!-- is not at the start of the line?
810 " Strange, can't find it.
814 let prevlnum = prevnonblank(v:lnum - 1)
815 let prevtext = getline(prevlnum)
816 let idx = match(prevtext, '^\s*\zs<!--')
818 " just below comment start, add a shiftwidth
819 return idx + s:ShiftWidth()
822 " Some files add 4 spaces just below a TODO line. It's difficult to detect
823 " the end of the TODO, so let's not do that.
825 " Align with the previous non-blank line.
826 return indent(prevlnum)
829 " Return the indent for conditional comment: <!--[ ![endif]-->
832 let curtext = getline(v:lnum)
833 if curtext =~ '\s*\zs<!\[endif\]-->'
834 " current line starts with end of comment, line up with comment start.
835 let lnum = search('<!--', 'bn')
840 return b:hi_indent.baseindent + s:ShiftWidth()
843 " When the "lnum" line ends in ">" find the line containing the matching "<".
844 func! HtmlIndent_FindTagStart(lnum)
846 " Avoids using the indent of a continuation line.
849 " - the matching line number or "lnum".
850 " - a flag indicating whether we found the end of a tag.
851 " This method is global so that HTML-like indenters can use it.
852 " To avoid matching " > " or " < " inside a string require that the opening
853 " "<" is followed by a word character and the closing ">" comes after a
854 " non-white character.
855 let idx = match(getline(a:lnum), '\S>\s*$')
857 call cursor(a:lnum, idx)
858 let lnum = searchpair('<\w', '' , '\S>', 'bW', '', max([a:lnum - b:html_indent_line_limit, 0]))
866 " Find the unclosed start tag from the current cursor position.
867 func! HtmlIndent_FindStartTag()
869 " The cursor must be on or before a closing tag.
870 " If found, positions the cursor at the match and returns the line number.
871 " Otherwise returns 0.
872 let tagname = matchstr(getline('.')[col('.') - 1:], '</\zs\w\+\ze')
873 let start_lnum = searchpair('<' . tagname . '\>', '', '</' . tagname . '\>', 'bW')
880 " Moves the cursor from a "<" to the matching ">".
881 func! HtmlIndent_FindTagEnd()
883 " Call this with the cursor on the "<" of a start tag.
884 " This will move the cursor to the ">" of the matching end tag or, when it's
885 " a self-closing tag, to the matching ">".
886 " Limited to look up to b:html_indent_line_limit lines away.
887 let text = getline('.')
888 let tagname = matchstr(text, '\w\+\|!--', col('.'))
890 call search('--\zs>')
891 elseif s:get_tag('/' . tagname) != 0
892 " tag with a closing tag, find matching "</tag>"
893 call searchpair('<' . tagname, '', '</' . tagname . '\zs>', 'W', '', line('.') + b:html_indent_line_limit)
895 " self-closing tag, find the ">"
896 call search('\S\zs>')
900 " Indenting inside a start tag. Return the correct indent or -1 if unknown.
901 func! s:InsideTag(foundHtmlString)
904 " Inside an attribute string.
905 " Align with the previous line or use an external function.
906 let lnum = v:lnum - 1
908 if exists('b:html_indent_tag_string_func')
909 return b:html_indent_tag_string_func(lnum)
915 " Should be another attribute: " attr="val". Align with the previous
920 let text = getline(lnum)
921 " Find a match with one of these, align with "attr":
925 " <tag>text</tag>text<tag attr=
926 " For long lines search for the first match, finding the last match
929 let idx = match(text, '.*\s\zs[_a-zA-Z0-9-]\+="')
931 let idx = match(text, '\s\zs[_a-zA-Z0-9-]\+="')
934 " Found the attribute. TODO: assumes spaces, no Tabs.
941 " THE MAIN INDENT FUNCTION. Return the amount of indent for v:lnum.
944 if prevnonblank(v:lnum - 1) < 1
945 " First non-blank line has no indent.
949 let curtext = tolower(getline(v:lnum))
950 let indentunit = s:ShiftWidth()
952 let b:hi_newstate = {}
953 let b:hi_newstate.lnum = v:lnum
955 " When syntax HL is enabled, detect we are inside a tag. Indenting inside
956 " a tag works very differently. Do not do this when the line starts with
957 " "<", it gets the "htmlTag" ID but we are not inside a tag then.
958 if curtext !~ '^\s*<'
960 let stack = synstack(v:lnum, col('.')) " assumes there are no tabs
961 let foundHtmlString = 0
962 for synid in reverse(stack)
963 let name = synIDattr(synid, "name")
964 if index(b:hi_insideStringNames, name) >= 0
965 let foundHtmlString = 1
966 elseif index(b:hi_insideTagNames, name) >= 0
967 " Yes, we are inside a tag.
968 let indent = s:InsideTag(foundHtmlString)
970 " Do not keep the state. TODO: could keep the block type.
971 let b:hi_indent.lnum = 0
978 " does the line start with a closing tag?
979 let swendtag = match(curtext, '^\s*</') >= 0
981 if prevnonblank(v:lnum - 1) == b:hi_indent.lnum && b:hi_lasttick == b:changedtick - 1
982 " use state (continue from previous line)
984 " start over (know nothing)
985 let b:hi_indent = s:FreshState(v:lnum)
988 if b:hi_indent.block >= 2
990 let endtag = s:endtags[b:hi_indent.block]
991 let blockend = stridx(curtext, endtag)
994 let b:hi_newstate.block = 0
995 " calc indent for REST OF LINE (may start more blocks):
996 call s:CountTagsAndState(strpart(curtext, blockend + strlen(endtag)))
997 if swendtag && b:hi_indent.block != 5
998 let indent = b:hi_indent.blocktagind + s:curind * indentunit
999 let b:hi_newstate.baseindent = indent + s:nextrel * indentunit
1001 let indent = s:Alien{b:hi_indent.block}()
1002 let b:hi_newstate.baseindent = b:hi_indent.blocktagind + s:nextrel * indentunit
1006 " indent this line with alien method
1007 let indent = s:Alien{b:hi_indent.block}()
1010 " not within a block - within usual html
1011 let b:hi_newstate.block = b:hi_indent.block
1013 " The current line starts with an end tag, align with its start tag.
1014 call cursor(v:lnum, 1)
1015 let start_lnum = HtmlIndent_FindStartTag()
1017 " check for the line starting with something inside a tag:
1018 " <sometag <- align here
1019 " attr=val><open> not here
1020 let text = getline(start_lnum)
1021 let angle = matchstr(text, '[<>]')
1023 call cursor(start_lnum, 1)
1025 let start_lnum = line('.')
1026 let text = getline(start_lnum)
1029 let indent = indent(start_lnum)
1031 let swendtag = match(text, '^\s*</') >= 0
1032 call s:CountITags(text[: col('.') - 2])
1033 let indent += s:nextrel * s:ShiftWidth()
1035 let indent += s:curind * s:ShiftWidth()
1039 " not sure what to do
1040 let indent = b:hi_indent.baseindent
1042 let b:hi_newstate.baseindent = indent
1044 call s:CountTagsAndState(curtext)
1045 let indent = b:hi_indent.baseindent
1046 let b:hi_newstate.baseindent = indent + (s:curind + s:nextrel) * indentunit
1050 let b:hi_lasttick = b:changedtick
1051 call extend(b:hi_indent, b:hi_newstate, "force")
1055 " Check user settings when loading this script the first time.
1056 call HtmlIndent_CheckUserSettings()
1058 let &cpo = s:cpo_save
1061 " vim: fdm=marker ts=8 sw=2 tw=78