All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
1 "TODO print messages when on visual mode. I only see VISUAL, not the messages.
3 " Function interface philosophy:
5 " - functions take arbitrary line numbers as parameters.
6 " Current cursor line is only a suitable default parameter.
8 " - only functions that bind directly to user actions:
10 " - print error messages.
11 " All intermediate functions limit themselves return `0` to indicate an error.
13 " - move the cursor. All other functions do not move the cursor.
15 " This is how you should view headers for the header mappings:
48 " For each level, contains the regexp that matches at that level only.
50 let s:levelRegexpDict = {
51 \ 1: '\v^(#[^#]@=|.+\n\=+$)',
52 \ 2: '\v^(##[^#]@=|.+\n-+$)',
55 \ 5: '\v^#####[^#]@=',
56 \ 6: '\v^######[^#]@='
59 " Matches any header level of any type.
61 " This could be deduced from `s:levelRegexpDict`, but it is more
62 " efficient to have a single regexp for this.
64 let s:headersRegexp = '\v^(#|.+\n(\=+|-+)$)'
66 " Returns the line number of the first header before `line`, called the
69 " If there is no current header, return `0`.
71 " @param a:1 The line to look the header of. Default value: `getpos('.')`.
73 function! s:GetHeaderLineNum(...)
80 if join(getline(l:l, l:l + 1), "\n") =~ s:headersRegexp
88 " - if inside a header goes to it.
89 " Return its line number.
91 " - if on top level outside any headers,
95 function! s:MoveToCurHeader()
96 let l:lineNum = s:GetHeaderLineNum()
98 call cursor(l:lineNum, 1)
100 echo 'outside any header'
106 " Move cursor to next header of any level.
108 " If there are no more headers, print a warning.
110 function! s:MoveToNextHeader()
111 if search(s:headersRegexp, 'W') == 0
113 echo 'no next header'
117 " Move cursor to previous header (before current) of any level.
119 " If it does not exist, print a warning.
121 function! s:MoveToPreviousHeader()
122 let l:curHeaderLineNumber = s:GetHeaderLineNum()
123 let l:noPreviousHeader = 0
124 if l:curHeaderLineNumber <= 1
125 let l:noPreviousHeader = 1
127 let l:previousHeaderLineNumber = s:GetHeaderLineNum(l:curHeaderLineNumber - 1)
128 if l:previousHeaderLineNumber == 0
129 let l:noPreviousHeader = 1
131 call cursor(l:previousHeaderLineNumber, 1)
134 if l:noPreviousHeader
135 echo 'no previous header'
139 " - if line is inside a header, return the header level (h1 -> 1, h2 -> 2, etc.).
141 " - if line is at top level outside any headers, return `0`.
143 function! s:GetHeaderLevel(...)
145 let l:line = line('.')
149 let l:linenum = s:GetHeaderLineNum(l:line)
151 return s:GetLevelOfHeaderAtLine(l:linenum)
157 " Return list of headers and their levels.
159 function! s:GetHeaderList()
160 let l:bufnr = bufnr('%')
161 let l:fenced_block = 0
162 let l:front_matter = 0
163 let l:header_list = []
164 let l:vim_markdown_frontmatter = get(g:, 'vim_markdown_frontmatter', 0)
166 for i in range(1, line('$'))
167 let l:lineraw = getline(i)
168 let l:l1 = getline(i+1)
169 let l:line = substitute(l:lineraw, '#', "\\\#", 'g')
170 " exclude lines in fenced code blocks
171 if l:line =~# '\v^[[:space:]>]*(`{3,}|\~{3,})\s*(\w+)?\s*$'
172 if l:fenced_block == 0
173 let l:fenced_block = 1
174 let l:fence_str = matchstr(l:line, '\v(`{3,}|\~{3,})')
175 elseif l:fenced_block == 1 && matchstr(l:line, '\v(`{3,}|\~{3,})') ==# l:fence_str
176 let l:fenced_block = 0
179 " exclude lines in frontmatters
180 elseif l:vim_markdown_frontmatter == 1
181 if l:front_matter == 1
183 let l:front_matter = 0
187 let l:front_matter = 1
191 " match line against header regex
192 if join(getline(i, i + 1), "\n") =~# s:headersRegexp && l:line =~# '^\S'
197 if l:is_header ==# 1 && l:fenced_block ==# 0 && l:front_matter ==# 0
198 " remove hashes from atx headers
199 if match(l:line, '^#') > -1
200 let l:line = substitute(l:line, '\v^#*[ ]*', '', '')
201 let l:line = substitute(l:line, '\v[ ]*#*$', '', '')
203 " append line to list
204 let l:level = s:GetHeaderLevel(i)
205 let l:item = {'level': l:level, 'text': l:line, 'lnum': i, 'bufnr': bufnr}
206 let l:header_list = l:header_list + [l:item]
212 " Returns the level of the header at the given line.
214 " If there is no header at the given line, returns `0`.
216 function! s:GetLevelOfHeaderAtLine(linenum)
217 let l:lines = join(getline(a:linenum, a:linenum + 1), "\n")
218 for l:key in keys(s:levelRegexpDict)
219 if l:lines =~ get(s:levelRegexpDict, l:key)
226 " Move cursor to parent header of the current header.
228 " If it does not exit, print a warning and do nothing.
230 function! s:MoveToParentHeader()
231 let l:linenum = s:GetParentHeaderLineNumber()
233 call setpos("''", getpos('.'))
234 call cursor(l:linenum, 1)
236 echo 'no parent header'
240 " Return the line number of the parent header of line `line`.
242 " If it has no parent, return `0`.
244 function! s:GetParentHeaderLineNumber(...)
246 let l:line = line('.')
250 let l:level = s:GetHeaderLevel(l:line)
252 let l:linenum = s:GetPreviousHeaderLineNumberAtLevel(l:level - 1, l:line)
258 " Return the line number of the previous header of given level.
259 " in relation to line `a:1`. If not given, `a:1 = getline()`
261 " `a:1` line is included, and this may return the current header.
265 function! s:GetNextHeaderLineNumberAtLevel(level, ...)
267 let l:line = line('.')
272 while(l:l <= line('$'))
273 if join(getline(l:l, l:l + 1), "\n") =~ get(s:levelRegexpDict, a:level)
281 " Return the line number of the previous header of given level.
282 " in relation to line `a:1`. If not given, `a:1 = getline()`
284 " `a:1` line is included, and this may return the current header.
288 function! s:GetPreviousHeaderLineNumberAtLevel(level, ...)
290 let l:line = line('.')
296 if join(getline(l:l, l:l + 1), "\n") =~ get(s:levelRegexpDict, a:level)
304 " Move cursor to next sibling header.
306 " If there is no next siblings, print a warning and don't move.
308 function! s:MoveToNextSiblingHeader()
309 let l:curHeaderLineNumber = s:GetHeaderLineNum()
310 let l:curHeaderLevel = s:GetLevelOfHeaderAtLine(l:curHeaderLineNumber)
311 let l:curHeaderParentLineNumber = s:GetParentHeaderLineNumber()
312 let l:nextHeaderSameLevelLineNumber = s:GetNextHeaderLineNumberAtLevel(l:curHeaderLevel, l:curHeaderLineNumber + 1)
313 let l:noNextSibling = 0
314 if l:nextHeaderSameLevelLineNumber == 0
315 let l:noNextSibling = 1
317 let l:nextHeaderSameLevelParentLineNumber = s:GetParentHeaderLineNumber(l:nextHeaderSameLevelLineNumber)
318 if l:curHeaderParentLineNumber == l:nextHeaderSameLevelParentLineNumber
319 call cursor(l:nextHeaderSameLevelLineNumber, 1)
321 let l:noNextSibling = 1
325 echo 'no next sibling header'
329 " Move cursor to previous sibling header.
331 " If there is no previous siblings, print a warning and do nothing.
333 function! s:MoveToPreviousSiblingHeader()
334 let l:curHeaderLineNumber = s:GetHeaderLineNum()
335 let l:curHeaderLevel = s:GetLevelOfHeaderAtLine(l:curHeaderLineNumber)
336 let l:curHeaderParentLineNumber = s:GetParentHeaderLineNumber()
337 let l:previousHeaderSameLevelLineNumber = s:GetPreviousHeaderLineNumberAtLevel(l:curHeaderLevel, l:curHeaderLineNumber - 1)
338 let l:noPreviousSibling = 0
339 if l:previousHeaderSameLevelLineNumber == 0
340 let l:noPreviousSibling = 1
342 let l:previousHeaderSameLevelParentLineNumber = s:GetParentHeaderLineNumber(l:previousHeaderSameLevelLineNumber)
343 if l:curHeaderParentLineNumber == l:previousHeaderSameLevelParentLineNumber
344 call cursor(l:previousHeaderSameLevelLineNumber, 1)
346 let l:noPreviousSibling = 1
349 if l:noPreviousSibling
350 echo 'no previous sibling header'
356 let l:window_type = a:1
358 let l:window_type = 'vertical'
362 let l:cursor_line = line('.')
363 let l:cursor_header = 0
364 let l:header_list = s:GetHeaderList()
365 let l:indented_header_list = []
366 if len(l:header_list) == 0
367 echom 'Toc: No headers.'
370 let l:header_max_len = 0
371 let l:vim_markdown_toc_autofit = get(g:, 'vim_markdown_toc_autofit', 0)
372 for h in l:header_list
373 " set header number of the cursor position
374 if l:cursor_header == 0
375 let l:header_line = h.lnum
376 if l:header_line == l:cursor_line
377 let l:cursor_header = index(l:header_list, h) + 1
378 elseif l:header_line > l:cursor_line
379 let l:cursor_header = index(l:header_list, h)
382 " indent header based on level
383 let l:text = repeat(' ', h.level-1) . h.text
384 " keep track of the longest header size (heading level + title)
385 let l:total_len = strdisplaywidth(l:text)
386 if l:total_len > l:header_max_len
387 let l:header_max_len = l:total_len
389 " append indented line to list
390 let l:item = {'lnum': h.lnum, 'text': l:text, 'valid': 1, 'bufnr': h.bufnr, 'col': 1}
391 let l:indented_header_list = l:indented_header_list + [l:item]
393 call setloclist(0, l:indented_header_list)
395 if l:window_type ==# 'horizontal'
397 elseif l:window_type ==# 'vertical'
399 " auto-fit toc window when possible to shrink it
400 if (&columns/2) > l:header_max_len && l:vim_markdown_toc_autofit == 1
401 " header_max_len + 1 space for first header + 3 spaces for line numbers
402 execute 'vertical resize ' . (l:header_max_len + 1 + 3)
404 execute 'vertical resize ' . (&columns/2)
406 elseif l:window_type ==# 'tab'
412 for i in range(1, line('$'))
413 " this is the location-list data for the current item
414 let d = getloclist(0)[i-1]
415 call setline(i, d.text)
418 setlocal nomodifiable
419 execute 'normal! ' . l:cursor_header . 'G'
422 function! s:InsertToc(format, ...)
424 if type(a:1) != type(0)
426 echomsg '[vim-markdown] Invalid argument, must be an integer >= 2.'
430 let l:max_level = a:1
433 echomsg '[vim-markdown] Maximum level cannot be smaller than 2.'
442 let l:header_list = s:GetHeaderList()
443 if len(l:header_list) == 0
444 echom 'InsertToc: No headers.'
448 if a:format ==# 'numbers'
450 for header in l:header_list
455 let l:max_h2_number_len = strlen(string(l:h2_count))
457 let l:max_h2_number_len = 0
461 for header in l:header_list
462 let l:level = header.level
464 " skip level-1 headers
466 elseif l:max_level != 0 && l:level > l:max_level
467 " skip unwanted levels
470 " list of level-2 headers can be bullets or numbers
471 if a:format ==# 'bullets'
476 let l:number_len = strlen(string(l:h2_count))
477 let l:indent = repeat(' ', l:max_h2_number_len - l:number_len)
478 let l:marker = l:h2_count . '. '
481 let l:indent = repeat(' ', l:max_h2_number_len + 2 * (l:level - 2))
484 let l:text = '[' . header.text . ']'
485 let l:link = '(#' . substitute(tolower(header.text), '\v[ ]+', '-', 'g') . ')'
486 let l:line = l:indent . l:marker . l:text . l:link
487 let l:toc = l:toc + [l:line]
490 call append(line('.'), l:toc)
493 " Convert Setex headers in range `line1 .. line2` to Atx.
495 " Return the number of conversions.
497 function! s:SetexToAtx(line1, line2)
498 let l:originalNumLines = line('$')
499 execute 'silent! ' . a:line1 . ',' . a:line2 . 'substitute/\v(.*\S.*)\n\=+$/# \1/'
501 let l:changed = l:originalNumLines - line('$')
502 execute 'silent! ' . a:line1 . ',' . (a:line2 - l:changed) . 'substitute/\v(.*\S.*)\n-+$/## \1'
503 return l:originalNumLines - line('$')
506 " If `a:1` is 0, decrease the level of all headers in range `line1 .. line2`.
508 " Otherwise, increase the level. `a:1` defaults to `0`.
510 function! s:HeaderDecrease(line1, line2, ...)
517 let l:forbiddenLevel = 6
518 let l:replaceLevels = [5, 1]
521 let l:forbiddenLevel = 1
522 let l:replaceLevels = [2, 6]
523 let l:levelDelta = -1
525 for l:line in range(a:line1, a:line2)
526 if join(getline(l:line, l:line + 1), "\n") =~ s:levelRegexpDict[l:forbiddenLevel]
527 echomsg 'There is an h' . l:forbiddenLevel . ' at line ' . l:line . '. Aborting.'
531 let l:numSubstitutions = s:SetexToAtx(a:line1, a:line2)
532 let l:flags = (&gdefault ? '' : 'g')
533 for l:level in range(replaceLevels[0], replaceLevels[1], -l:levelDelta)
534 execute 'silent! ' . a:line1 . ',' . (a:line2 - l:numSubstitutions) . 'substitute/' . s:levelRegexpDict[l:level] . '/' . repeat('#', l:level + l:levelDelta) . '/' . l:flags
538 " Format table under cursor.
540 " Depends on Tabularize.
542 function! s:TableFormat()
543 let l:pos = getpos('.')
545 if get(g:, 'vim_markdown_borderless_table', 0)
546 " add `|` to the beginning of the line if it isn't present
549 execute 'silent .,''}s/\v^(\s{0,})\|?([^\|])/\1|\2/e'
551 " add `|` to the end of the line if it isn't present
554 execute 'silent .,''}s/\v([^\|])\|?(\s{0,})$/\1|\2/e'
558 " Search instead of `normal! j` because of the table at beginning of file edge case.
561 " Remove everything that is not a pipe, colon or hyphen next to a colon othewise
562 " well formated tables would grow because of addition of 2 spaces on the separator
563 " line by Tabularize /|.
564 let l:flags = (&gdefault ? '' : 'g')
565 execute 's/\(:\@<!-:\@!\|[^|:-]\)//e' . l:flags
566 execute 's/--/-/e' . l:flags
567 Tabularize /\(\\\)\@<!|
568 " Move colons for alignment to left or right side of the cell.
569 execute 's/:\( \+\)|/\1:|/e' . l:flags
570 execute 's/|\( \+\):/|:\1/e' . l:flags
571 execute 's/|:\?\zs[ -]\+\ze:\?|/\=repeat("-", len(submatch(0)))/' . l:flags
572 call setpos('.', l:pos)
575 " Wrapper to do move commands in visual mode.
577 function! s:VisMove(f)
582 " Map in both normal and visual modes.
584 function! s:MapNormVis(rhs,lhs)
585 execute 'nn <buffer><silent> ' . a:rhs . ' :call ' . a:lhs . '()<cr>'
586 execute 'vn <buffer><silent> ' . a:rhs . ' <esc>:call <sid>VisMove(''' . a:lhs . ''')<cr>'
591 " - step +1 for right, -1 for left
593 " TODO: multiple lines.
595 function! s:FindCornerOfSyntax(lnum, col, step)
597 let l:syn = synIDattr(synID(a:lnum, l:col, 1), 'name')
598 while synIDattr(synID(a:lnum, l:col, 1), 'name') ==# l:syn
601 return l:col - a:step
604 " Return the next position of the given syntax name,
605 " inclusive on the given position.
607 " TODO: multiple lines
609 function! s:FindNextSyntax(lnum, col, name)
612 while synIDattr(synID(a:lnum, l:col, 1), 'name') !=# a:name
615 return [a:lnum, l:col]
618 function! s:FindCornersOfSyntax(lnum, col)
619 return [<sid>FindLeftOfSyntax(a:lnum, a:col), <sid>FindRightOfSyntax(a:lnum, a:col)]
622 function! s:FindRightOfSyntax(lnum, col)
623 return <sid>FindCornerOfSyntax(a:lnum, a:col, 1)
626 function! s:FindLeftOfSyntax(lnum, col)
627 return <sid>FindCornerOfSyntax(a:lnum, a:col, -1)
632 " - a string with the the URL for the link under the cursor
633 " - an empty string if the cursor is not on a link
637 " - multiline support
638 " - give an error if the separator does is not on a link
640 function! s:Markdown_GetUrlForPosition(lnum, col)
643 let l:syn = synIDattr(synID(l:lnum, l:col, 1), 'name')
645 if l:syn ==# 'mkdInlineURL' || l:syn ==# 'mkdURL' || l:syn ==# 'mkdLinkDefTarget'
647 elseif l:syn ==# 'mkdLink'
648 let [l:lnum, l:col] = <sid>FindNextSyntax(l:lnum, l:col, 'mkdURL')
650 elseif l:syn ==# 'mkdDelimiter'
651 let l:line = getline(l:lnum)
652 let l:char = l:line[col - 1]
655 elseif l:char ==# '>' || l:char ==# ')'
657 elseif l:char ==# '[' || l:char ==# ']' || l:char ==# '('
658 let [l:lnum, l:col] = <sid>FindNextSyntax(l:lnum, l:col, 'mkdURL')
666 let [l:left, l:right] = <sid>FindCornersOfSyntax(l:lnum, l:col)
667 return getline(l:lnum)[l:left - 1 : l:right - 1]
670 " Front end for GetUrlForPosition.
672 function! s:OpenUrlUnderCursor()
673 let l:url = s:Markdown_GetUrlForPosition(line('.'), col('.'))
675 if l:url =~? 'http[s]\?:\/\/[[:alnum:]%\/_#.-]*'
678 let l:url = expand(expand('%:h').'/'.l:url)
680 call s:VersionAwareNetrwBrowseX(l:url)
682 echomsg 'The cursor is not on a link.'
686 " We need a definition guard because we invoke 'edit' which will reload this
687 " script while this function is running. We must not replace it.
688 if !exists('*s:EditUrlUnderCursor')
689 function s:EditUrlUnderCursor()
690 let l:editmethod = ''
691 " determine how to open the linked file (split, tab, etc)
692 if exists('g:vim_markdown_edit_url_in')
693 if g:vim_markdown_edit_url_in ==# 'tab'
694 let l:editmethod = 'tabnew'
695 elseif g:vim_markdown_edit_url_in ==# 'vsplit'
696 let l:editmethod = 'vsp'
697 elseif g:vim_markdown_edit_url_in ==# 'hsplit'
698 let l:editmethod = 'sp'
700 let l:editmethod = 'edit'
703 " default to current buffer
704 let l:editmethod = 'edit'
706 let l:url = s:Markdown_GetUrlForPosition(line('.'), col('.'))
708 if get(g:, 'vim_markdown_autowrite', 0)
712 if get(g:, 'vim_markdown_follow_anchor', 0)
713 let l:parts = split(l:url, '#', 1)
715 let [l:url, l:anchor] = parts
716 let l:anchorexpr = get(g:, 'vim_markdown_anchorexpr', '')
717 if l:anchorexpr !=# ''
718 let l:anchor = eval(substitute(
719 \ l:anchorexpr, 'v:anchor',
720 \ escape('"'.l:anchor.'"', '"'), ''))
726 if get(g:, 'vim_markdown_no_extensions_in_markdown', 0)
727 " use another file extension if preferred
728 if exists('g:vim_markdown_auto_extension_ext')
729 let l:ext = '.'.g:vim_markdown_auto_extension_ext
734 let l:url = fnameescape(fnamemodify(expand('%:h').'/'.l:url.l:ext, ':.'))
735 execute l:editmethod l:url
738 call search(l:anchor, 's')
741 execute l:editmethod . ' <cfile>'
746 function! s:VersionAwareNetrwBrowseX(url)
747 if has('patch-7.4.567')
748 call netrw#BrowseX(a:url, 0)
750 call netrw#NetrwBrowseX(a:url, 0)
754 function! s:MapNotHasmapto(lhs, rhs)
755 if !hasmapto('<Plug>' . a:rhs)
756 execute 'nmap <buffer>' . a:lhs . ' <Plug>' . a:rhs
757 execute 'vmap <buffer>' . a:lhs . ' <Plug>' . a:rhs
761 call <sid>MapNormVis('<Plug>Markdown_MoveToNextHeader', '<sid>MoveToNextHeader')
762 call <sid>MapNormVis('<Plug>Markdown_MoveToPreviousHeader', '<sid>MoveToPreviousHeader')
763 call <sid>MapNormVis('<Plug>Markdown_MoveToNextSiblingHeader', '<sid>MoveToNextSiblingHeader')
764 call <sid>MapNormVis('<Plug>Markdown_MoveToPreviousSiblingHeader', '<sid>MoveToPreviousSiblingHeader')
765 call <sid>MapNormVis('<Plug>Markdown_MoveToParentHeader', '<sid>MoveToParentHeader')
766 call <sid>MapNormVis('<Plug>Markdown_MoveToCurHeader', '<sid>MoveToCurHeader')
767 nnoremap <Plug>Markdown_OpenUrlUnderCursor :call <sid>OpenUrlUnderCursor()<cr>
768 nnoremap <Plug>Markdown_EditUrlUnderCursor :call <sid>EditUrlUnderCursor()<cr>
770 if !get(g:, 'vim_markdown_no_default_key_mappings', 0)
771 call <sid>MapNotHasmapto(']]', 'Markdown_MoveToNextHeader')
772 call <sid>MapNotHasmapto('[[', 'Markdown_MoveToPreviousHeader')
773 call <sid>MapNotHasmapto('][', 'Markdown_MoveToNextSiblingHeader')
774 call <sid>MapNotHasmapto('[]', 'Markdown_MoveToPreviousSiblingHeader')
775 call <sid>MapNotHasmapto(']u', 'Markdown_MoveToParentHeader')
776 call <sid>MapNotHasmapto(']h', 'Markdown_MoveToCurHeader')
777 call <sid>MapNotHasmapto('gx', 'Markdown_OpenUrlUnderCursor')
778 call <sid>MapNotHasmapto('ge', 'Markdown_EditUrlUnderCursor')
781 command! -buffer -range=% HeaderDecrease call s:HeaderDecrease(<line1>, <line2>)
782 command! -buffer -range=% HeaderIncrease call s:HeaderDecrease(<line1>, <line2>, 1)
783 command! -buffer -range=% SetexToAtx call s:SetexToAtx(<line1>, <line2>)
784 command! -buffer -range TableFormat call s:TableFormat()
785 command! -buffer Toc call s:Toc()
786 command! -buffer Toch call s:Toc('horizontal')
787 command! -buffer Tocv call s:Toc('vertical')
788 command! -buffer Toct call s:Toc('tab')
789 command! -buffer -nargs=? InsertToc call s:InsertToc('bullets', <args>)
790 command! -buffer -nargs=? InsertNToc call s:InsertToc('numbers', <args>)
792 " Heavily based on vim-notes - http://peterodding.com/code/vim/notes/
793 if exists('g:vim_markdown_fenced_languages')
794 let s:filetype_dict = {}
795 for s:filetype in g:vim_markdown_fenced_languages
796 let key = matchstr(s:filetype, '[^=]*')
797 let val = matchstr(s:filetype, '[^=]*$')
798 let s:filetype_dict[key] = val
801 let s:filetype_dict = {
809 function! s:MarkdownHighlightSources(force)
810 " Syntax highlight source code embedded in notes.
811 " Look for code blocks in the current file
813 for line in getline(1, '$')
814 let ft = matchstr(line, '\(`\{3,}\|\~\{3,}\)\s*\zs[0-9A-Za-z_+-]*\ze.*')
815 if !empty(ft) && ft !~# '^\d*$' | let filetypes[ft] = 1 | endif
817 if !exists('b:mkd_known_filetypes')
818 let b:mkd_known_filetypes = {}
820 if !exists('b:mkd_included_filetypes')
821 " set syntax file name included
822 let b:mkd_included_filetypes = {}
824 if !a:force && (b:mkd_known_filetypes == filetypes || empty(filetypes))
828 " Now we're ready to actually highlight the code blocks.
829 let startgroup = 'mkdCodeStart'
830 let endgroup = 'mkdCodeEnd'
831 for ft in keys(filetypes)
832 if a:force || !has_key(b:mkd_known_filetypes, ft)
833 if has_key(s:filetype_dict, ft)
834 let filetype = s:filetype_dict[ft]
838 let group = 'mkdSnippet' . toupper(substitute(filetype, '[+-]', '_', 'g'))
839 if !has_key(b:mkd_included_filetypes, filetype)
840 let include = s:SyntaxInclude(filetype)
841 let b:mkd_included_filetypes[filetype] = 1
843 let include = '@' . toupper(filetype)
845 let command_backtick = 'syntax region %s matchgroup=%s start="^\s*`\{3,}\s*%s.*$" matchgroup=%s end="\s*`\{3,}$" keepend contains=%s%s'
846 let command_tilde = 'syntax region %s matchgroup=%s start="^\s*\~\{3,}\s*%s.*$" matchgroup=%s end="\s*\~\{3,}$" keepend contains=%s%s'
847 execute printf(command_backtick, group, startgroup, ft, endgroup, include, has('conceal') && get(g:, 'vim_markdown_conceal', 1) && get(g:, 'vim_markdown_conceal_code_blocks', 1) ? ' concealends' : '')
848 execute printf(command_tilde, group, startgroup, ft, endgroup, include, has('conceal') && get(g:, 'vim_markdown_conceal', 1) && get(g:, 'vim_markdown_conceal_code_blocks', 1) ? ' concealends' : '')
849 execute printf('syntax cluster mkdNonListItem add=%s', group)
851 let b:mkd_known_filetypes[ft] = 1
856 function! s:SyntaxInclude(filetype)
857 " Include the syntax highlighting of another {filetype}.
858 let grouplistname = '@' . toupper(a:filetype)
859 " Unset the name of the current syntax while including the other syntax
860 " because some syntax scripts do nothing when "b:current_syntax" is set
861 if exists('b:current_syntax')
862 let syntax_save = b:current_syntax
863 unlet b:current_syntax
866 execute 'syntax include' grouplistname 'syntax/' . a:filetype . '.vim'
867 execute 'syntax include' grouplistname 'after/syntax/' . a:filetype . '.vim'
869 " Ignore missing scripts
871 " Restore the name of the current syntax
872 if exists('syntax_save')
873 let b:current_syntax = syntax_save
874 elseif exists('b:current_syntax')
875 unlet b:current_syntax
880 function! s:IsHighlightSourcesEnabledForBuffer()
881 " Enable for markdown buffers, and for liquid buffers with markdown format
882 return &filetype =~# 'markdown' || get(b:, 'liquid_subtype', '') =~# 'markdown'
885 function! s:MarkdownRefreshSyntax(force)
886 " Use != to compare &syntax's value to use the same logic run on
887 " $VIMRUNTIME/syntax/synload.vim.
889 " vint: next-line -ProhibitEqualTildeOperator
890 if s:IsHighlightSourcesEnabledForBuffer() && line('$') > 1 && &syntax != 'OFF'
891 call s:MarkdownHighlightSources(a:force)
895 function! s:MarkdownClearSyntaxVariables()
896 if s:IsHighlightSourcesEnabledForBuffer()
897 unlet! b:mkd_included_filetypes
902 " These autocmd calling s:MarkdownRefreshSyntax need to be kept in sync with
903 " the autocmds calling s:MarkdownSetupFolding in after/ftplugin/markdown.vim.
905 autocmd BufWinEnter <buffer> call s:MarkdownRefreshSyntax(1)
906 autocmd BufUnload <buffer> call s:MarkdownClearSyntaxVariables()
907 autocmd BufWritePost <buffer> call s:MarkdownRefreshSyntax(0)
908 autocmd InsertEnter,InsertLeave <buffer> call s:MarkdownRefreshSyntax(0)
909 autocmd CursorHold,CursorHoldI <buffer> call s:MarkdownRefreshSyntax(0)