markdown.vim 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. "TODO print messages when on visual mode. I only see VISUAL, not the messages.
  2. " Function interface phylosophy:
  3. "
  4. " - functions take arbitrary line numbers as parameters.
  5. " Current cursor line is only a suitable default parameter.
  6. "
  7. " - only functions that bind directly to user actions:
  8. "
  9. " - print error messages.
  10. " All intermediate functions limit themselves return `0` to indicate an error.
  11. "
  12. " - move the cursor. All other functions do not move the cursor.
  13. "
  14. " This is how you should view headers for the header mappings:
  15. "
  16. " |BUFFER
  17. " |
  18. " |Outside any header
  19. " |
  20. " a-+# a
  21. " |
  22. " |Inside a
  23. " |
  24. " a-+
  25. " b-+## b
  26. " |
  27. " |inside b
  28. " |
  29. " b-+
  30. " c-+### c
  31. " |
  32. " |Inside c
  33. " |
  34. " c-+
  35. " d-|# d
  36. " |
  37. " |Inside d
  38. " |
  39. " d-+
  40. " e-|e
  41. " |====
  42. " |
  43. " |Inside e
  44. " |
  45. " e-+
  46. " For each level, contains the regexp that matches at that level only.
  47. "
  48. let s:levelRegexpDict = {
  49. \ 1: '\v^(#[^#]@=|.+\n\=+$)',
  50. \ 2: '\v^(##[^#]@=|.+\n-+$)',
  51. \ 3: '\v^###[^#]@=',
  52. \ 4: '\v^####[^#]@=',
  53. \ 5: '\v^#####[^#]@=',
  54. \ 6: '\v^######[^#]@='
  55. \ }
  56. " Maches any header level of any type.
  57. "
  58. " This could be deduced from `s:levelRegexpDict`, but it is more
  59. " efficient to have a single regexp for this.
  60. "
  61. let s:headersRegexp = '\v^(#|.+\n(\=+|-+)$)'
  62. " Returns the line number of the first header before `line`, called the
  63. " current header.
  64. "
  65. " If there is no current header, return `0`.
  66. "
  67. " @param a:1 The line to look the header of. Default value: `getpos('.')`.
  68. "
  69. function! s:GetHeaderLineNum(...)
  70. if a:0 == 0
  71. let l:l = line('.')
  72. else
  73. let l:l = a:1
  74. endif
  75. while(l:l > 0)
  76. if join(getline(l:l, l:l + 1), "\n") =~ s:headersRegexp
  77. return l:l
  78. endif
  79. let l:l -= 1
  80. endwhile
  81. return 0
  82. endfunction
  83. " - if inside a header goes to it.
  84. " Return its line number.
  85. "
  86. " - if on top level outside any headers,
  87. " print a warning
  88. " Return `0`.
  89. "
  90. function! s:MoveToCurHeader()
  91. let l:lineNum = s:GetHeaderLineNum()
  92. if l:lineNum != 0
  93. call cursor(l:lineNum, 1)
  94. else
  95. echo 'outside any header'
  96. "normal! gg
  97. endif
  98. return l:lineNum
  99. endfunction
  100. " Move cursor to next header of any level.
  101. "
  102. " If there are no more headers, print a warning.
  103. "
  104. function! s:MoveToNextHeader()
  105. if search(s:headersRegexp, 'W') == 0
  106. "normal! G
  107. echo 'no next header'
  108. endif
  109. endfunction
  110. " Move cursor to previous header (before current) of any level.
  111. "
  112. " If it does not exist, print a warning.
  113. "
  114. function! s:MoveToPreviousHeader()
  115. let l:curHeaderLineNumber = s:GetHeaderLineNum()
  116. let l:noPreviousHeader = 0
  117. if l:curHeaderLineNumber <= 1
  118. let l:noPreviousHeader = 1
  119. else
  120. let l:previousHeaderLineNumber = s:GetHeaderLineNum(l:curHeaderLineNumber - 1)
  121. if l:previousHeaderLineNumber == 0
  122. let l:noPreviousHeader = 1
  123. else
  124. call cursor(l:previousHeaderLineNumber, 1)
  125. endif
  126. endif
  127. if l:noPreviousHeader
  128. echo 'no previous header'
  129. endif
  130. endfunction
  131. " - if line is inside a header, return the header level (h1 -> 1, h2 -> 2, etc.).
  132. "
  133. " - if line is at top level outside any headers, return `0`.
  134. "
  135. function! s:GetHeaderLevel(...)
  136. if a:0 == 0
  137. let l:line = line('.')
  138. else
  139. let l:line = a:1
  140. endif
  141. let l:linenum = s:GetHeaderLineNum(l:line)
  142. if l:linenum != 0
  143. return s:GetLevelOfHeaderAtLine(l:linenum)
  144. else
  145. return 0
  146. endif
  147. endfunction
  148. " Returns the level of the header at the given line.
  149. "
  150. " If there is no header at the given line, returns `0`.
  151. "
  152. function! s:GetLevelOfHeaderAtLine(linenum)
  153. let l:lines = join(getline(a:linenum, a:linenum + 1), "\n")
  154. for l:key in keys(s:levelRegexpDict)
  155. if l:lines =~ get(s:levelRegexpDict, l:key)
  156. return l:key
  157. endif
  158. endfor
  159. return 0
  160. endfunction
  161. " Move cursor to parent header of the current header.
  162. "
  163. " If it does not exit, print a warning and do nothing.
  164. "
  165. function! s:MoveToParentHeader()
  166. let l:linenum = s:GetParentHeaderLineNumber()
  167. if l:linenum != 0
  168. call cursor(l:linenum, 1)
  169. else
  170. echo 'no parent header'
  171. endif
  172. endfunction
  173. " Return the line number of the parent header of line `line`.
  174. "
  175. " If it has no parent, return `0`.
  176. "
  177. function! s:GetParentHeaderLineNumber(...)
  178. if a:0 == 0
  179. let l:line = line('.')
  180. else
  181. let l:line = a:1
  182. endif
  183. let l:level = s:GetHeaderLevel(l:line)
  184. if l:level > 1
  185. let l:linenum = s:GetPreviousHeaderLineNumberAtLevel(l:level - 1, l:line)
  186. return l:linenum
  187. endif
  188. return 0
  189. endfunction
  190. " Return the line number of the previous header of given level.
  191. " in relation to line `a:1`. If not given, `a:1 = getline()`
  192. "
  193. " `a:1` line is included, and this may return the current header.
  194. "
  195. " If none return 0.
  196. "
  197. function! s:GetNextHeaderLineNumberAtLevel(level, ...)
  198. if a:0 < 1
  199. let l:line = line('.')
  200. else
  201. let l:line = a:1
  202. endif
  203. let l:l = l:line
  204. while(l:l <= line('$'))
  205. if join(getline(l:l, l:l + 1), "\n") =~ get(s:levelRegexpDict, a:level)
  206. return l:l
  207. endif
  208. let l:l += 1
  209. endwhile
  210. return 0
  211. endfunction
  212. " Return the line number of the previous header of given level.
  213. " in relation to line `a:1`. If not given, `a:1 = getline()`
  214. "
  215. " `a:1` line is included, and this may return the current header.
  216. "
  217. " If none return 0.
  218. "
  219. function! s:GetPreviousHeaderLineNumberAtLevel(level, ...)
  220. if a:0 == 0
  221. let l:line = line('.')
  222. else
  223. let l:line = a:1
  224. endif
  225. let l:l = l:line
  226. while(l:l > 0)
  227. if join(getline(l:l, l:l + 1), "\n") =~ get(s:levelRegexpDict, a:level)
  228. return l:l
  229. endif
  230. let l:l -= 1
  231. endwhile
  232. return 0
  233. endfunction
  234. " Move cursor to next sibling header.
  235. "
  236. " If there is no next siblings, print a warning and don't move.
  237. "
  238. function! s:MoveToNextSiblingHeader()
  239. let l:curHeaderLineNumber = s:GetHeaderLineNum()
  240. let l:curHeaderLevel = s:GetLevelOfHeaderAtLine(l:curHeaderLineNumber)
  241. let l:curHeaderParentLineNumber = s:GetParentHeaderLineNumber()
  242. let l:nextHeaderSameLevelLineNumber = s:GetNextHeaderLineNumberAtLevel(l:curHeaderLevel, l:curHeaderLineNumber + 1)
  243. let l:noNextSibling = 0
  244. if l:nextHeaderSameLevelLineNumber == 0
  245. let l:noNextSibling = 1
  246. else
  247. let l:nextHeaderSameLevelParentLineNumber = s:GetParentHeaderLineNumber(l:nextHeaderSameLevelLineNumber)
  248. if l:curHeaderParentLineNumber == l:nextHeaderSameLevelParentLineNumber
  249. call cursor(l:nextHeaderSameLevelLineNumber, 1)
  250. else
  251. let l:noNextSibling = 1
  252. endif
  253. endif
  254. if l:noNextSibling
  255. echo 'no next sibling header'
  256. endif
  257. endfunction
  258. " Move cursor to previous sibling header.
  259. "
  260. " If there is no previous siblings, print a warning and do nothing.
  261. "
  262. function! s:MoveToPreviousSiblingHeader()
  263. let l:curHeaderLineNumber = s:GetHeaderLineNum()
  264. let l:curHeaderLevel = s:GetLevelOfHeaderAtLine(l:curHeaderLineNumber)
  265. let l:curHeaderParentLineNumber = s:GetParentHeaderLineNumber()
  266. let l:previousHeaderSameLevelLineNumber = s:GetPreviousHeaderLineNumberAtLevel(l:curHeaderLevel, l:curHeaderLineNumber - 1)
  267. let l:noPreviousSibling = 0
  268. if l:previousHeaderSameLevelLineNumber == 0
  269. let l:noPreviousSibling = 1
  270. else
  271. let l:previousHeaderSameLevelParentLineNumber = s:GetParentHeaderLineNumber(l:previousHeaderSameLevelLineNumber)
  272. if l:curHeaderParentLineNumber == l:previousHeaderSameLevelParentLineNumber
  273. call cursor(l:previousHeaderSameLevelLineNumber, 1)
  274. else
  275. let l:noPreviousSibling = 1
  276. endif
  277. endif
  278. if l:noPreviousSibling
  279. echo 'no previous sibling header'
  280. endif
  281. endfunction
  282. function! s:Toc(...)
  283. if a:0 > 0
  284. let l:window_type = a:1
  285. else
  286. let l:window_type = 'vertical'
  287. endif
  288. let l:bufnr = bufnr('%')
  289. let l:cursor_line = line('.')
  290. let l:cursor_header = 0
  291. let l:fenced_block = 0
  292. let l:front_matter = 0
  293. let l:header_list = []
  294. let l:header_max_len = 0
  295. let l:vim_markdown_toc_autofit = get(g:, "vim_markdown_toc_autofit", 0)
  296. let l:vim_markdown_frontmatter = get(g:, "vim_markdown_frontmatter", 0)
  297. for i in range(1, line('$'))
  298. let l:lineraw = getline(i)
  299. let l:l1 = getline(i+1)
  300. let l:line = substitute(l:lineraw, "#", "\\\#", "g")
  301. if l:line =~ '````*' || l:line =~ '\~\~\~\~*'
  302. if l:fenced_block == 0
  303. let l:fenced_block = 1
  304. elseif l:fenced_block == 1
  305. let l:fenced_block = 0
  306. endif
  307. elseif l:vim_markdown_frontmatter == 1
  308. if l:front_matter == 1
  309. if l:line == '---'
  310. let l:front_matter = 0
  311. endif
  312. elseif i == 1
  313. if l:line == '---'
  314. let l:front_matter = 1
  315. endif
  316. endif
  317. endif
  318. if l:line =~ '^#\+' || (l:l1 =~ '^=\+\s*$' || l:l1 =~ '^-\+\s*$') && l:line =~ '^\S'
  319. let l:is_header = 1
  320. else
  321. let l:is_header = 0
  322. endif
  323. if l:is_header == 1 && l:fenced_block == 0 && l:front_matter == 0
  324. " append line to location list
  325. let l:item = {'lnum': i, 'text': l:line, 'valid': 1, 'bufnr': l:bufnr, 'col': 1}
  326. let l:header_list = l:header_list + [l:item]
  327. " set header number of the cursor position
  328. if l:cursor_header == 0
  329. if i == l:cursor_line
  330. let l:cursor_header = len(l:header_list)
  331. elseif i > l:cursor_line
  332. let l:cursor_header = len(l:header_list) - 1
  333. endif
  334. endif
  335. " keep track of the longest header size (heading level + title)
  336. let l:total_len = stridx(l:line, ' ') + strdisplaywidth(l:line)
  337. if l:total_len > l:header_max_len
  338. let l:header_max_len = l:total_len
  339. endif
  340. endif
  341. endfor
  342. call setloclist(0, l:header_list)
  343. if len(l:header_list) == 0
  344. echom "Toc: No headers."
  345. return
  346. endif
  347. if l:window_type ==# 'horizontal'
  348. lopen
  349. elseif l:window_type ==# 'vertical'
  350. vertical lopen
  351. " auto-fit toc window when possible to shrink it
  352. if (&columns/2) > l:header_max_len && l:vim_markdown_toc_autofit == 1
  353. execute 'vertical resize ' . (l:header_max_len + 1)
  354. else
  355. execute 'vertical resize ' . (&columns/2)
  356. endif
  357. elseif l:window_type ==# 'tab'
  358. tab lopen
  359. else
  360. lopen
  361. endif
  362. setlocal modifiable
  363. for i in range(1, line('$'))
  364. " this is the location-list data for the current item
  365. let d = getloclist(0)[i-1]
  366. " atx headers
  367. if match(d.text, "^#") > -1
  368. let l:level = len(matchstr(d.text, '#*', 'g'))-1
  369. let d.text = substitute(d.text, '\v^#*[ ]*', '', '')
  370. let d.text = substitute(d.text, '\v[ ]*#*$', '', '')
  371. " setex headers
  372. else
  373. let l:next_line = getbufline(d.bufnr, d.lnum+1)
  374. if match(l:next_line, "=") > -1
  375. let l:level = 0
  376. elseif match(l:next_line, "-") > -1
  377. let l:level = 1
  378. endif
  379. endif
  380. call setline(i, repeat(' ', l:level). d.text)
  381. endfor
  382. setlocal nomodified
  383. setlocal nomodifiable
  384. execute 'normal! ' . l:cursor_header . 'G'
  385. endfunction
  386. " Convert Setex headers in range `line1 .. line2` to Atx.
  387. "
  388. " Return the number of conversions.
  389. "
  390. function! s:SetexToAtx(line1, line2)
  391. let l:originalNumLines = line('$')
  392. execute 'silent! ' . a:line1 . ',' . a:line2 . 'substitute/\v(.*\S.*)\n\=+$/# \1/'
  393. execute 'silent! ' . a:line1 . ',' . a:line2 . 'substitute/\v(.*\S.*)\n-+$/## \1/'
  394. return l:originalNumLines - line('$')
  395. endfunction
  396. " If `a:1` is 0, decrease the level of all headers in range `line1 .. line2`.
  397. "
  398. " Otherwise, increase the level. `a:1` defaults to `0`.
  399. "
  400. function! s:HeaderDecrease(line1, line2, ...)
  401. if a:0 > 0
  402. let l:increase = a:1
  403. else
  404. let l:increase = 0
  405. endif
  406. if l:increase
  407. let l:forbiddenLevel = 6
  408. let l:replaceLevels = [5, 1]
  409. let l:levelDelta = 1
  410. else
  411. let l:forbiddenLevel = 1
  412. let l:replaceLevels = [2, 6]
  413. let l:levelDelta = -1
  414. endif
  415. for l:line in range(a:line1, a:line2)
  416. if join(getline(l:line, l:line + 1), "\n") =~ s:levelRegexpDict[l:forbiddenLevel]
  417. echomsg 'There is an h' . l:forbiddenLevel . ' at line ' . l:line . '. Aborting.'
  418. return
  419. endif
  420. endfor
  421. let l:numSubstitutions = s:SetexToAtx(a:line1, a:line2)
  422. let l:flags = (&gdefault ? '' : 'g')
  423. for l:level in range(replaceLevels[0], replaceLevels[1], -l:levelDelta)
  424. execute 'silent! ' . a:line1 . ',' . (a:line2 - l:numSubstitutions) . 'substitute/' . s:levelRegexpDict[l:level] . '/' . repeat('#', l:level + l:levelDelta) . '/' . l:flags
  425. endfor
  426. endfunction
  427. " Format table under cursor.
  428. "
  429. " Depends on Tabularize.
  430. "
  431. function! s:TableFormat()
  432. let l:pos = getpos('.')
  433. normal! {
  434. " Search instead of `normal! j` because of the table at beginning of file edge case.
  435. call search('|')
  436. normal! j
  437. " Remove everything that is not a pipe, colon or hyphen next to a colon othewise
  438. " well formated tables would grow because of addition of 2 spaces on the separator
  439. " line by Tabularize /|.
  440. let l:flags = (&gdefault ? '' : 'g')
  441. execute 's/\(:\@<!-:\@!\|[^|:-]\)//e' . l:flags
  442. execute 's/--/-/e' . l:flags
  443. Tabularize /|
  444. " Move colons for alignment to left or right side of the cell.
  445. execute 's/:\( \+\)|/\1:|/e' . l:flags
  446. execute 's/|\( \+\):/|:\1/e' . l:flags
  447. execute 's/ /-/' . l:flags
  448. call setpos('.', l:pos)
  449. endfunction
  450. " Wrapper to do move commands in visual mode.
  451. "
  452. function! s:VisMove(f)
  453. norm! gv
  454. call function(a:f)()
  455. endfunction
  456. " Map in both normal and visual modes.
  457. "
  458. function! s:MapNormVis(rhs,lhs)
  459. execute 'nn <buffer><silent> ' . a:rhs . ' :call ' . a:lhs . '()<cr>'
  460. execute 'vn <buffer><silent> ' . a:rhs . ' <esc>:call <sid>VisMove(''' . a:lhs . ''')<cr>'
  461. endfunction
  462. " Parameters:
  463. "
  464. " - step +1 for right, -1 for left
  465. "
  466. " TODO: multiple lines.
  467. "
  468. function! s:FindCornerOfSyntax(lnum, col, step)
  469. let l:col = a:col
  470. let l:syn = synIDattr(synID(a:lnum, l:col, 1), 'name')
  471. while synIDattr(synID(a:lnum, l:col, 1), 'name') ==# l:syn
  472. let l:col += a:step
  473. endwhile
  474. return l:col - a:step
  475. endfunction
  476. " Return the next position of the given syntax name,
  477. " inclusive on the given position.
  478. "
  479. " TODO: multiple lines
  480. "
  481. function! s:FindNextSyntax(lnum, col, name)
  482. let l:col = a:col
  483. let l:step = 1
  484. while synIDattr(synID(a:lnum, l:col, 1), 'name') !=# a:name
  485. let l:col += l:step
  486. endwhile
  487. return [a:lnum, l:col]
  488. endfunction
  489. function! s:FindCornersOfSyntax(lnum, col)
  490. return [<sid>FindLeftOfSyntax(a:lnum, a:col), <sid>FindRightOfSyntax(a:lnum, a:col)]
  491. endfunction
  492. function! s:FindRightOfSyntax(lnum, col)
  493. return <sid>FindCornerOfSyntax(a:lnum, a:col, 1)
  494. endfunction
  495. function! s:FindLeftOfSyntax(lnum, col)
  496. return <sid>FindCornerOfSyntax(a:lnum, a:col, -1)
  497. endfunction
  498. " Returns:
  499. "
  500. " - a string with the the URL for the link under the cursor
  501. " - an empty string if the cursor is not on a link
  502. "
  503. " TODO
  504. "
  505. " - multiline support
  506. " - give an error if the separator does is not on a link
  507. "
  508. function! s:Markdown_GetUrlForPosition(lnum, col)
  509. let l:lnum = a:lnum
  510. let l:col = a:col
  511. let l:syn = synIDattr(synID(l:lnum, l:col, 1), 'name')
  512. if l:syn ==# 'mkdInlineURL' || l:syn ==# 'mkdURL' || l:syn ==# 'mkdLinkDefTarget'
  513. " Do nothing.
  514. elseif l:syn ==# 'mkdLink'
  515. let [l:lnum, l:col] = <sid>FindNextSyntax(l:lnum, l:col, 'mkdURL')
  516. let l:syn = 'mkdURL'
  517. elseif l:syn ==# 'mkdDelimiter'
  518. let l:line = getline(l:lnum)
  519. let l:char = l:line[col - 1]
  520. if l:char ==# '<'
  521. let l:col += 1
  522. elseif l:char ==# '>' || l:char ==# ')'
  523. let l:col -= 1
  524. elseif l:char ==# '[' || l:char ==# ']' || l:char ==# '('
  525. let [l:lnum, l:col] = <sid>FindNextSyntax(l:lnum, l:col, 'mkdURL')
  526. else
  527. return ''
  528. endif
  529. else
  530. return ''
  531. endif
  532. let [l:left, l:right] = <sid>FindCornersOfSyntax(l:lnum, l:col)
  533. return getline(l:lnum)[l:left - 1 : l:right - 1]
  534. endfunction
  535. " Front end for GetUrlForPosition.
  536. "
  537. function! s:OpenUrlUnderCursor()
  538. let l:url = s:Markdown_GetUrlForPosition(line('.'), col('.'))
  539. if l:url != ''
  540. call s:VersionAwareNetrwBrowseX(l:url)
  541. else
  542. echomsg 'The cursor is not on a link.'
  543. endif
  544. endfunction
  545. " We need a definition guard because we invoke 'edit' which will reload this
  546. " script while this function is running. We must not replace it.
  547. if !exists('*s:EditUrlUnderCursor')
  548. function s:EditUrlUnderCursor()
  549. let l:url = s:Markdown_GetUrlForPosition(line('.'), col('.'))
  550. if l:url != ''
  551. if get(g:, 'vim_markdown_autowrite', 0)
  552. write
  553. endif
  554. let l:anchor = ''
  555. if get(g:, 'vim_markdown_follow_anchor', 0)
  556. let l:parts = split(l:url, '#', 1)
  557. if len(l:parts) == 2
  558. let [l:url, l:anchor] = parts
  559. let l:anchorexpr = get(g:, 'vim_markdown_anchorexpr', '')
  560. if l:anchorexpr != ''
  561. let l:anchor = eval(substitute(
  562. \ l:anchorexpr, 'v:anchor',
  563. \ escape('"'.l:anchor.'"', '"'), ''))
  564. endif
  565. endif
  566. endif
  567. if l:url != ''
  568. let l:ext = ''
  569. if get(g:, 'vim_markdown_no_extensions_in_markdown', 0)
  570. " use another file extension if preferred
  571. if exists('g:vim_markdown_auto_extension_ext')
  572. let l:ext = '.'.g:vim_markdown_auto_extension_ext
  573. else
  574. let l:ext = '.md'
  575. endif
  576. endif
  577. let l:url = fnameescape(fnamemodify(expand('%:h').'/'.l:url.l:ext, ':.'))
  578. let l:editmethod = ''
  579. " determine how to open the linked file (split, tab, etc)
  580. if exists('g:vim_markdown_edit_url_in')
  581. if g:vim_markdown_edit_url_in == 'tab'
  582. let l:editmethod = 'tabnew'
  583. elseif g:vim_markdown_edit_url_in == 'vsplit'
  584. let l:editmethod = 'vsp'
  585. elseif g:vim_markdown_edit_url_in == 'hsplit'
  586. let l:editmethod = 'sp'
  587. else
  588. let l:editmethod = 'edit'
  589. endif
  590. else
  591. " default to current buffer
  592. let l:editmethod = 'edit'
  593. endif
  594. execute l:editmethod l:url
  595. endif
  596. if l:anchor != ''
  597. silent! execute '/'.l:anchor
  598. endif
  599. else
  600. echomsg 'The cursor is not on a link.'
  601. endif
  602. endfunction
  603. endif
  604. function! s:VersionAwareNetrwBrowseX(url)
  605. if has('patch-7.4.567')
  606. call netrw#BrowseX(a:url, 0)
  607. else
  608. call netrw#NetrwBrowseX(a:url, 0)
  609. endif
  610. endf
  611. function! s:MapNotHasmapto(lhs, rhs)
  612. if !hasmapto('<Plug>' . a:rhs)
  613. execute 'nmap <buffer>' . a:lhs . ' <Plug>' . a:rhs
  614. execute 'vmap <buffer>' . a:lhs . ' <Plug>' . a:rhs
  615. endif
  616. endfunction
  617. call <sid>MapNormVis('<Plug>Markdown_MoveToNextHeader', '<sid>MoveToNextHeader')
  618. call <sid>MapNormVis('<Plug>Markdown_MoveToPreviousHeader', '<sid>MoveToPreviousHeader')
  619. call <sid>MapNormVis('<Plug>Markdown_MoveToNextSiblingHeader', '<sid>MoveToNextSiblingHeader')
  620. call <sid>MapNormVis('<Plug>Markdown_MoveToPreviousSiblingHeader', '<sid>MoveToPreviousSiblingHeader')
  621. call <sid>MapNormVis('<Plug>Markdown_MoveToParentHeader', '<sid>MoveToParentHeader')
  622. call <sid>MapNormVis('<Plug>Markdown_MoveToCurHeader', '<sid>MoveToCurHeader')
  623. nnoremap <Plug>Markdown_OpenUrlUnderCursor :call <sid>OpenUrlUnderCursor()<cr>
  624. nnoremap <Plug>Markdown_EditUrlUnderCursor :call <sid>EditUrlUnderCursor()<cr>
  625. if !get(g:, 'vim_markdown_no_default_key_mappings', 0)
  626. call <sid>MapNotHasmapto(']]', 'Markdown_MoveToNextHeader')
  627. call <sid>MapNotHasmapto('[[', 'Markdown_MoveToPreviousHeader')
  628. call <sid>MapNotHasmapto('][', 'Markdown_MoveToNextSiblingHeader')
  629. call <sid>MapNotHasmapto('[]', 'Markdown_MoveToPreviousSiblingHeader')
  630. call <sid>MapNotHasmapto(']u', 'Markdown_MoveToParentHeader')
  631. call <sid>MapNotHasmapto(']c', 'Markdown_MoveToCurHeader')
  632. call <sid>MapNotHasmapto('gx', 'Markdown_OpenUrlUnderCursor')
  633. call <sid>MapNotHasmapto('ge', 'Markdown_EditUrlUnderCursor')
  634. endif
  635. command! -buffer -range=% HeaderDecrease call s:HeaderDecrease(<line1>, <line2>)
  636. command! -buffer -range=% HeaderIncrease call s:HeaderDecrease(<line1>, <line2>, 1)
  637. command! -buffer -range=% SetexToAtx call s:SetexToAtx(<line1>, <line2>)
  638. command! -buffer TableFormat call s:TableFormat()
  639. command! -buffer Toc call s:Toc()
  640. command! -buffer Toch call s:Toc('horizontal')
  641. command! -buffer Tocv call s:Toc('vertical')
  642. command! -buffer Toct call s:Toc('tab')
  643. " Heavily based on vim-notes - http://peterodding.com/code/vim/notes/
  644. if exists('g:vim_markdown_fenced_languages')
  645. let s:filetype_dict = {}
  646. for s:filetype in g:vim_markdown_fenced_languages
  647. let key = matchstr(s:filetype, "[^=]*")
  648. let val = matchstr(s:filetype, "[^=]*$")
  649. let s:filetype_dict[key] = val
  650. endfor
  651. else
  652. let s:filetype_dict = {
  653. \ 'c++': 'cpp',
  654. \ 'viml': 'vim',
  655. \ 'bash': 'sh',
  656. \ 'ini': 'dosini'
  657. \ }
  658. endif
  659. function! s:MarkdownHighlightSources(force)
  660. " Syntax highlight source code embedded in notes.
  661. " Look for code blocks in the current file
  662. let filetypes = {}
  663. for line in getline(1, '$')
  664. let ft = matchstr(line, '```\s*\zs[0-9A-Za-z_+-]*')
  665. if !empty(ft) && ft !~ '^\d*$' | let filetypes[ft] = 1 | endif
  666. endfor
  667. if !exists('b:mkd_known_filetypes')
  668. let b:mkd_known_filetypes = {}
  669. endif
  670. if !exists('b:mkd_included_filetypes')
  671. " set syntax file name included
  672. let b:mkd_included_filetypes = {}
  673. endif
  674. if !a:force && (b:mkd_known_filetypes == filetypes || empty(filetypes))
  675. return
  676. endif
  677. " Now we're ready to actually highlight the code blocks.
  678. let startgroup = 'mkdCodeStart'
  679. let endgroup = 'mkdCodeEnd'
  680. for ft in keys(filetypes)
  681. if a:force || !has_key(b:mkd_known_filetypes, ft)
  682. if has_key(s:filetype_dict, ft)
  683. let filetype = s:filetype_dict[ft]
  684. else
  685. let filetype = ft
  686. endif
  687. let group = 'mkdSnippet' . toupper(substitute(filetype, "[+-]", "_", "g"))
  688. if !has_key(b:mkd_included_filetypes, filetype)
  689. let include = s:SyntaxInclude(filetype)
  690. let b:mkd_included_filetypes[filetype] = 1
  691. else
  692. let include = '@' . toupper(filetype)
  693. endif
  694. let command = 'syntax region %s matchgroup=%s start="^\s*```\s*%s$" matchgroup=%s end="\s*```$" keepend contains=%s%s'
  695. execute printf(command, group, startgroup, ft, endgroup, include, has('conceal') && get(g:, 'vim_markdown_conceal', 1) && get(g:, 'vim_markdown_conceal_code_blocks', 1) ? ' concealends' : '')
  696. execute printf('syntax cluster mkdNonListItem add=%s', group)
  697. let b:mkd_known_filetypes[ft] = 1
  698. endif
  699. endfor
  700. endfunction
  701. function! s:SyntaxInclude(filetype)
  702. " Include the syntax highlighting of another {filetype}.
  703. let grouplistname = '@' . toupper(a:filetype)
  704. " Unset the name of the current syntax while including the other syntax
  705. " because some syntax scripts do nothing when "b:current_syntax" is set
  706. if exists('b:current_syntax')
  707. let syntax_save = b:current_syntax
  708. unlet b:current_syntax
  709. endif
  710. try
  711. execute 'syntax include' grouplistname 'syntax/' . a:filetype . '.vim'
  712. execute 'syntax include' grouplistname 'after/syntax/' . a:filetype . '.vim'
  713. catch /E484/
  714. " Ignore missing scripts
  715. endtry
  716. " Restore the name of the current syntax
  717. if exists('syntax_save')
  718. let b:current_syntax = syntax_save
  719. elseif exists('b:current_syntax')
  720. unlet b:current_syntax
  721. endif
  722. return grouplistname
  723. endfunction
  724. function! s:MarkdownRefreshSyntax(force)
  725. if &filetype =~ 'markdown' && line('$') > 1
  726. call s:MarkdownHighlightSources(a:force)
  727. endif
  728. endfunction
  729. function! s:MarkdownClearSyntaxVariables()
  730. if &filetype =~ 'markdown'
  731. unlet! b:mkd_included_filetypes
  732. endif
  733. endfunction
  734. augroup Mkd
  735. " These autocmd calling s:MarkdownRefreshSyntax need to be kept in sync with
  736. " the autocmds calling s:MarkdownSetupFolding in after/ftplugin/markdown.vim.
  737. autocmd! * <buffer>
  738. autocmd BufWinEnter <buffer> call s:MarkdownRefreshSyntax(1)
  739. autocmd BufUnload <buffer> call s:MarkdownClearSyntaxVariables()
  740. autocmd BufWritePost <buffer> call s:MarkdownRefreshSyntax(0)
  741. autocmd InsertEnter,InsertLeave <buffer> call s:MarkdownRefreshSyntax(0)
  742. autocmd CursorHold,CursorHoldI <buffer> call s:MarkdownRefreshSyntax(0)
  743. augroup END