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 phylosophy:
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 " Maches 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 " Returns the level of the header at the given line.
159 " If there is no header at the given line, returns `0`.
161 function! s:GetLevelOfHeaderAtLine(linenum)
162 let l:lines = join(getline(a:linenum, a:linenum + 1), "\n")
163 for l:key in keys(s:levelRegexpDict)
164 if l:lines =~ get(s:levelRegexpDict, l:key)
171 " Move cursor to parent header of the current header.
173 " If it does not exit, print a warning and do nothing.
175 function! s:MoveToParentHeader()
176 let l:linenum = s:GetParentHeaderLineNumber()
178 call cursor(l:linenum, 1)
180 echo 'no parent header'
184 " Return the line number of the parent header of line `line`.
186 " If it has no parent, return `0`.
188 function! s:GetParentHeaderLineNumber(...)
190 let l:line = line('.')
194 let l:level = s:GetHeaderLevel(l:line)
196 let l:linenum = s:GetPreviousHeaderLineNumberAtLevel(l:level - 1, l:line)
202 " Return the line number of the previous header of given level.
203 " in relation to line `a:1`. If not given, `a:1 = getline()`
205 " `a:1` line is included, and this may return the current header.
209 function! s:GetNextHeaderLineNumberAtLevel(level, ...)
211 let l:line = line('.')
216 while(l:l <= line('$'))
217 if join(getline(l:l, l:l + 1), "\n") =~ get(s:levelRegexpDict, a:level)
225 " Return the line number of the previous header of given level.
226 " in relation to line `a:1`. If not given, `a:1 = getline()`
228 " `a:1` line is included, and this may return the current header.
232 function! s:GetPreviousHeaderLineNumberAtLevel(level, ...)
234 let l:line = line('.')
240 if join(getline(l:l, l:l + 1), "\n") =~ get(s:levelRegexpDict, a:level)
248 " Move cursor to next sibling header.
250 " If there is no next siblings, print a warning and don't move.
252 function! s:MoveToNextSiblingHeader()
253 let l:curHeaderLineNumber = s:GetHeaderLineNum()
254 let l:curHeaderLevel = s:GetLevelOfHeaderAtLine(l:curHeaderLineNumber)
255 let l:curHeaderParentLineNumber = s:GetParentHeaderLineNumber()
256 let l:nextHeaderSameLevelLineNumber = s:GetNextHeaderLineNumberAtLevel(l:curHeaderLevel, l:curHeaderLineNumber + 1)
257 let l:noNextSibling = 0
258 if l:nextHeaderSameLevelLineNumber == 0
259 let l:noNextSibling = 1
261 let l:nextHeaderSameLevelParentLineNumber = s:GetParentHeaderLineNumber(l:nextHeaderSameLevelLineNumber)
262 if l:curHeaderParentLineNumber == l:nextHeaderSameLevelParentLineNumber
263 call cursor(l:nextHeaderSameLevelLineNumber, 1)
265 let l:noNextSibling = 1
269 echo 'no next sibling header'
273 " Move cursor to previous sibling header.
275 " If there is no previous siblings, print a warning and do nothing.
277 function! s:MoveToPreviousSiblingHeader()
278 let l:curHeaderLineNumber = s:GetHeaderLineNum()
279 let l:curHeaderLevel = s:GetLevelOfHeaderAtLine(l:curHeaderLineNumber)
280 let l:curHeaderParentLineNumber = s:GetParentHeaderLineNumber()
281 let l:previousHeaderSameLevelLineNumber = s:GetPreviousHeaderLineNumberAtLevel(l:curHeaderLevel, l:curHeaderLineNumber - 1)
282 let l:noPreviousSibling = 0
283 if l:previousHeaderSameLevelLineNumber == 0
284 let l:noPreviousSibling = 1
286 let l:previousHeaderSameLevelParentLineNumber = s:GetParentHeaderLineNumber(l:previousHeaderSameLevelLineNumber)
287 if l:curHeaderParentLineNumber == l:previousHeaderSameLevelParentLineNumber
288 call cursor(l:previousHeaderSameLevelLineNumber, 1)
290 let l:noPreviousSibling = 1
293 if l:noPreviousSibling
294 echo 'no previous sibling header'
300 let l:window_type = a:1
302 let l:window_type = 'vertical'
306 let b:bufnr = bufnr('%')
307 let b:fenced_block = 0
308 let b:header_list = []
309 let l:header_max_len = 0
310 for i in range(1, line('$'))
311 let l:lineraw = getline(i)
312 let l:l1 = getline(i+1)
313 let l:line = substitute(l:lineraw, "#", "\\\#", "g")
314 if l:line =~ '````*' || l:line =~ '\~\~\~\~*'
315 if b:fenced_block == 0
316 let b:fenced_block = 1
317 elseif b:fenced_block == 1
318 let b:fenced_block = 0
321 if l:line =~ '^#\+' || (l:l1 =~ '^=\+\s*$' || l:l1 =~ '^-\+\s*$') && l:line =~ '^\S'
326 if b:is_header == 1 && b:fenced_block == 0
327 " append line to location list
328 let b:item = {'lnum': i, 'text': l:line, 'valid': 1, 'bufnr': b:bufnr, 'col': 1}
329 let b:header_list = b:header_list + [b:item]
332 if len(b:header_list) == 0
333 echom "Toc: No headers."
336 call setloclist(0, b:header_list)
338 if l:window_type ==# 'horizontal'
340 elseif l:window_type ==# 'vertical'
342 let &winwidth=(&columns/2)
343 elseif l:window_type ==# 'tab'
349 for i in range(1, line('$'))
350 " this is the location-list data for the current item
351 let d = getloclist(0)[i-1]
353 if match(d.text, "^#") > -1
354 let l:level = len(matchstr(d.text, '#*', 'g'))-1
355 let d.text = substitute(d.text, '\v^#*[ ]*', '', '')
356 let d.text = substitute(d.text, '\v[ ]*#*$', '', '')
359 let l:next_line = getbufline(d.bufnr, d.lnum+1)
360 if match(l:next_line, "=") > -1
362 elseif match(l:next_line, "-") > -1
366 call setline(i, repeat(' ', l:level). d.text)
369 setlocal nomodifiable
373 " Convert Setex headers in range `line1 .. line2` to Atx.
375 " Return the number of conversions.
377 function! s:SetexToAtx(line1, line2)
378 let l:originalNumLines = line('$')
379 execute 'silent! ' . a:line1 . ',' . a:line2 . 'substitute/\v(.*\S.*)\n\=+$/# \1/'
380 execute 'silent! ' . a:line1 . ',' . a:line2 . 'substitute/\v(.*\S.*)\n-+$/## \1/'
381 return l:originalNumLines - line('$')
384 " If `a:1` is 0, decrease the level of all headers in range `line1 .. line2`.
386 " Otherwise, increase the level. `a:1` defaults to `0`.
388 function! s:HeaderDecrease(line1, line2, ...)
395 let l:forbiddenLevel = 6
396 let l:replaceLevels = [5, 1]
399 let l:forbiddenLevel = 1
400 let l:replaceLevels = [2, 6]
401 let l:levelDelta = -1
403 for l:line in range(a:line1, a:line2)
404 if join(getline(l:line, l:line + 1), "\n") =~ s:levelRegexpDict[l:forbiddenLevel]
405 echomsg 'There is an h' . l:forbiddenLevel . ' at line ' . l:line . '. Aborting.'
409 let l:numSubstitutions = s:SetexToAtx(a:line1, a:line2)
410 let l:flags = (&gdefault ? '' : 'g')
411 for l:level in range(replaceLevels[0], replaceLevels[1], -l:levelDelta)
412 execute 'silent! ' . a:line1 . ',' . (a:line2 - l:numSubstitutions) . 'substitute/' . s:levelRegexpDict[l:level] . '/' . repeat('#', l:level + l:levelDelta) . '/' . l:flags
416 " Format table under cursor.
418 " Depends on Tabularize.
420 function! s:TableFormat()
421 let l:pos = getpos('.')
423 " Search instead of `normal! j` because of the table at beginning of file edge case.
426 " Remove everything that is not a pipe othewise well formated tables would grow
427 " because of addition of 2 spaces on the separator line by Tabularize /|.
428 let l:flags = (&gdefault ? '' : 'g')
429 execute 's/[^|]//' . l:flags
431 execute 's/ /-/' . l:flags
432 call setpos('.', l:pos)
435 " Wrapper to do move commands in visual mode.
437 function! s:VisMove(f)
442 " Map in both normal and visual modes.
444 function! s:MapNormVis(rhs,lhs)
445 execute 'nn <buffer><silent> ' . a:rhs . ' :call ' . a:lhs . '()<cr>'
446 execute 'vn <buffer><silent> ' . a:rhs . ' <esc>:call <sid>VisMove(''' . a:lhs . ''')<cr>'
451 " - step +1 for right, -1 for left
453 " TODO: multiple lines.
455 function! s:FindCornerOfSyntax(lnum, col, step)
457 let l:syn = synIDattr(synID(a:lnum, l:col, 1), 'name')
458 while synIDattr(synID(a:lnum, l:col, 1), 'name') ==# l:syn
461 return l:col - a:step
464 " Return the next position of the given syntax name,
465 " inclusive on the given position.
467 " TODO: multiple lines
469 function! s:FindNextSyntax(lnum, col, name)
472 while synIDattr(synID(a:lnum, l:col, 1), 'name') !=# a:name
475 return [a:lnum, l:col]
478 function! s:FindCornersOfSyntax(lnum, col)
479 return [<sid>FindLeftOfSyntax(a:lnum, a:col), <sid>FindRightOfSyntax(a:lnum, a:col)]
482 function! s:FindRightOfSyntax(lnum, col)
483 return <sid>FindCornerOfSyntax(a:lnum, a:col, 1)
486 function! s:FindLeftOfSyntax(lnum, col)
487 return <sid>FindCornerOfSyntax(a:lnum, a:col, -1)
492 " - a string with the the URL for the link under the cursor
493 " - an empty string if the cursor is not on a link
497 " - multiline support
498 " - give an error if the separator does is not on a link
500 function! s:Markdown_GetUrlForPosition(lnum, col)
503 let l:syn = synIDattr(synID(l:lnum, l:col, 1), 'name')
505 if l:syn ==# 'mkdInlineURL' || l:syn ==# 'mkdURL' || l:syn ==# 'mkdLinkDefTarget'
507 elseif l:syn ==# 'mkdLink'
508 let [l:lnum, l:col] = <sid>FindNextSyntax(l:lnum, l:col, 'mkdURL')
510 elseif l:syn ==# 'mkdDelimiter'
511 let l:line = getline(l:lnum)
512 let l:char = l:line[col - 1]
515 elseif l:char ==# '>' || l:char ==# ')'
517 elseif l:char ==# '[' || l:char ==# ']' || l:char ==# '('
518 let [l:lnum, l:col] = <sid>FindNextSyntax(l:lnum, l:col, 'mkdURL')
526 let [l:left, l:right] = <sid>FindCornersOfSyntax(l:lnum, l:col)
527 return getline(l:lnum)[l:left - 1 : l:right - 1]
530 " Front end for GetUrlForPosition.
532 function! s:OpenUrlUnderCursor()
533 let l:url = s:Markdown_GetUrlForPosition(line('.'), col('.'))
535 call s:VersionAwareNetrwBrowseX(l:url)
537 echomsg 'The cursor is not on a link.'
541 function! s:VersionAwareNetrwBrowseX(url)
542 if has('patch-7.4.567')
543 call netrw#BrowseX(a:url, 0)
545 call netrw#NetrwBrowseX(a:url, 0)
549 function! s:MapNotHasmapto(lhs, rhs)
550 if !hasmapto('<Plug>' . a:rhs)
551 execute 'nmap <buffer>' . a:lhs . ' <Plug>' . a:rhs
552 execute 'vmap <buffer>' . a:lhs . ' <Plug>' . a:rhs
556 call <sid>MapNormVis('<Plug>Markdown_MoveToNextHeader', '<sid>MoveToNextHeader')
557 call <sid>MapNormVis('<Plug>Markdown_MoveToPreviousHeader', '<sid>MoveToPreviousHeader')
558 call <sid>MapNormVis('<Plug>Markdown_MoveToNextSiblingHeader', '<sid>MoveToNextSiblingHeader')
559 call <sid>MapNormVis('<Plug>Markdown_MoveToPreviousSiblingHeader', '<sid>MoveToPreviousSiblingHeader')
560 call <sid>MapNormVis('<Plug>Markdown_MoveToParentHeader', '<sid>MoveToParentHeader')
561 call <sid>MapNormVis('<Plug>Markdown_MoveToCurHeader', '<sid>MoveToCurHeader')
562 nnoremap <Plug>Markdown_OpenUrlUnderCursor :call <sid>OpenUrlUnderCursor()<cr>
564 if !get(g:, 'vim_markdown_no_default_key_mappings', 0)
565 call <sid>MapNotHasmapto(']]', 'Markdown_MoveToNextHeader')
566 call <sid>MapNotHasmapto('[[', 'Markdown_MoveToPreviousHeader')
567 call <sid>MapNotHasmapto('][', 'Markdown_MoveToNextSiblingHeader')
568 call <sid>MapNotHasmapto('[]', 'Markdown_MoveToPreviousSiblingHeader')
569 call <sid>MapNotHasmapto(']u', 'Markdown_MoveToParentHeader')
570 call <sid>MapNotHasmapto(']c', 'Markdown_MoveToCurHeader')
571 call <sid>MapNotHasmapto('gx', 'Markdown_OpenUrlUnderCursor')
574 command! -buffer -range=% HeaderDecrease call s:HeaderDecrease(<line1>, <line2>)
575 command! -buffer -range=% HeaderIncrease call s:HeaderDecrease(<line1>, <line2>, 1)
576 command! -buffer -range=% SetexToAtx call s:SetexToAtx(<line1>, <line2>)
577 command! -buffer TableFormat call s:TableFormat()
578 command! -buffer Toc call s:Toc()
579 command! -buffer Toch call s:Toc('horizontal')
580 command! -buffer Tocv call s:Toc('vertical')
581 command! -buffer Toct call s:Toc('tab')
583 " Heavily based on vim-notes - http://peterodding.com/code/vim/notes/
584 let s:filetype_dict = {
589 function! s:Markdown_highlight_sources(force)
590 " Syntax highlight source code embedded in notes.
591 " Look for code blocks in the current file
593 for line in getline(1, '$')
594 let ft = matchstr(line, '```\zs[0-9A-Za-z_+-]*')
595 if !empty(ft) && ft !~ '^\d*$' | let filetypes[ft] = 1 | endif
597 if !exists('b:mkd_known_filetypes')
598 let b:mkd_known_filetypes = {}
600 if !a:force && (b:mkd_known_filetypes == filetypes || empty(filetypes))
604 " Now we're ready to actually highlight the code blocks.
605 let startgroup = 'mkdCodeStart'
606 let endgroup = 'mkdCodeEnd'
607 for ft in keys(filetypes)
608 if a:force || !has_key(b:mkd_known_filetypes, ft)
609 if has_key(s:filetype_dict, ft)
610 let filetype = s:filetype_dict[ft]
614 let group = 'mkdSnippet' . toupper(substitute(filetype, "[+-]", "_", "g"))
615 let include = s:syntax_include(filetype)
616 let command = 'syntax region %s matchgroup=%s start="^\s*```%s$" matchgroup=%s end="\s*```$" keepend contains=%s%s'
617 execute printf(command, group, startgroup, ft, endgroup, include, has('conceal') ? ' concealends' : '')
618 execute printf('syntax cluster mkdNonListItem add=%s', group)
620 let b:mkd_known_filetypes[ft] = 1
625 function! s:syntax_include(filetype)
626 " Include the syntax highlighting of another {filetype}.
627 let grouplistname = '@' . toupper(a:filetype)
628 " Unset the name of the current syntax while including the other syntax
629 " because some syntax scripts do nothing when "b:current_syntax" is set
630 if exists('b:current_syntax')
631 let syntax_save = b:current_syntax
632 unlet b:current_syntax
635 execute 'syntax include' grouplistname 'syntax/' . a:filetype . '.vim'
636 execute 'syntax include' grouplistname 'after/syntax/' . a:filetype . '.vim'
638 " Ignore missing scripts
640 " Restore the name of the current syntax
641 if exists('syntax_save')
642 let b:current_syntax = syntax_save
643 elseif exists('b:current_syntax')
644 unlet b:current_syntax
650 function! s:Markdown_refresh_syntax(force)
651 if &filetype == 'markdown' && line('$') > 1
652 call s:Markdown_highlight_sources(a:force)
658 au BufWinEnter * call s:Markdown_refresh_syntax(1)
659 au BufWritePost * call s:Markdown_refresh_syntax(0)
660 au InsertEnter,InsertLeave * call s:Markdown_refresh_syntax(0)
661 au CursorHold,CursorHoldI * call s:Markdown_refresh_syntax(0)