markdown.vim 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. " Return list of headers and their levels.
  149. "
  150. function! s:GetHeaderList()
  151. let l:bufnr = bufnr('%')
  152. let l:fenced_block = 0
  153. let l:front_matter = 0
  154. let l:header_list = []
  155. let l:vim_markdown_frontmatter = get(g:, 'vim_markdown_frontmatter', 0)
  156. for i in range(1, line('$'))
  157. let l:lineraw = getline(i)
  158. let l:l1 = getline(i+1)
  159. let l:line = substitute(l:lineraw, '#', "\\\#", 'g')
  160. " exclude lines in fenced code blocks
  161. if l:line =~# '````*' || l:line =~# '\~\~\~\~*'
  162. if l:fenced_block == 0
  163. let l:fenced_block = 1
  164. elseif l:fenced_block == 1
  165. let l:fenced_block = 0
  166. endif
  167. " exclude lines in frontmatters
  168. elseif l:vim_markdown_frontmatter == 1
  169. if l:front_matter == 1
  170. if l:line ==# '---'
  171. let l:front_matter = 0
  172. endif
  173. elseif i == 1
  174. if l:line ==# '---'
  175. let l:front_matter = 1
  176. endif
  177. endif
  178. endif
  179. " match line against header regex
  180. if join(getline(i, i + 1), "\n") =~# s:headersRegexp && l:line =~# '^\S'
  181. let l:is_header = 1
  182. else
  183. let l:is_header = 0
  184. endif
  185. if l:is_header ==# 1 && l:fenced_block ==# 0 && l:front_matter ==# 0
  186. " remove hashes from atx headers
  187. if match(l:line, '^#') > -1
  188. let l:line = substitute(l:line, '\v^#*[ ]*', '', '')
  189. let l:line = substitute(l:line, '\v[ ]*#*$', '', '')
  190. endif
  191. " append line to list
  192. let l:level = s:GetHeaderLevel(i)
  193. let l:item = {'level': l:level, 'text': l:line, 'lnum': i, 'bufnr': bufnr}
  194. let l:header_list = l:header_list + [l:item]
  195. endif
  196. endfor
  197. return l:header_list
  198. endfunction
  199. " Returns the level of the header at the given line.
  200. "
  201. " If there is no header at the given line, returns `0`.
  202. "
  203. function! s:GetLevelOfHeaderAtLine(linenum)
  204. let l:lines = join(getline(a:linenum, a:linenum + 1), "\n")
  205. for l:key in keys(s:levelRegexpDict)
  206. if l:lines =~ get(s:levelRegexpDict, l:key)
  207. return l:key
  208. endif
  209. endfor
  210. return 0
  211. endfunction
  212. " Move cursor to parent header of the current header.
  213. "
  214. " If it does not exit, print a warning and do nothing.
  215. "
  216. function! s:MoveToParentHeader()
  217. let l:linenum = s:GetParentHeaderLineNumber()
  218. if l:linenum != 0
  219. call setpos("''", getpos('.'))
  220. call cursor(l:linenum, 1)
  221. else
  222. echo 'no parent header'
  223. endif
  224. endfunction
  225. " Return the line number of the parent header of line `line`.
  226. "
  227. " If it has no parent, return `0`.
  228. "
  229. function! s:GetParentHeaderLineNumber(...)
  230. if a:0 == 0
  231. let l:line = line('.')
  232. else
  233. let l:line = a:1
  234. endif
  235. let l:level = s:GetHeaderLevel(l:line)
  236. if l:level > 1
  237. let l:linenum = s:GetPreviousHeaderLineNumberAtLevel(l:level - 1, l:line)
  238. return l:linenum
  239. endif
  240. return 0
  241. endfunction
  242. " Return the line number of the previous header of given level.
  243. " in relation to line `a:1`. If not given, `a:1 = getline()`
  244. "
  245. " `a:1` line is included, and this may return the current header.
  246. "
  247. " If none return 0.
  248. "
  249. function! s:GetNextHeaderLineNumberAtLevel(level, ...)
  250. if a:0 < 1
  251. let l:line = line('.')
  252. else
  253. let l:line = a:1
  254. endif
  255. let l:l = l:line
  256. while(l:l <= line('$'))
  257. if join(getline(l:l, l:l + 1), "\n") =~ get(s:levelRegexpDict, a:level)
  258. return l:l
  259. endif
  260. let l:l += 1
  261. endwhile
  262. return 0
  263. endfunction
  264. " Return the line number of the previous header of given level.
  265. " in relation to line `a:1`. If not given, `a:1 = getline()`
  266. "
  267. " `a:1` line is included, and this may return the current header.
  268. "
  269. " If none return 0.
  270. "
  271. function! s:GetPreviousHeaderLineNumberAtLevel(level, ...)
  272. if a:0 == 0
  273. let l:line = line('.')
  274. else
  275. let l:line = a:1
  276. endif
  277. let l:l = l:line
  278. while(l:l > 0)
  279. if join(getline(l:l, l:l + 1), "\n") =~ get(s:levelRegexpDict, a:level)
  280. return l:l
  281. endif
  282. let l:l -= 1
  283. endwhile
  284. return 0
  285. endfunction
  286. " Move cursor to next sibling header.
  287. "
  288. " If there is no next siblings, print a warning and don't move.
  289. "
  290. function! s:MoveToNextSiblingHeader()
  291. let l:curHeaderLineNumber = s:GetHeaderLineNum()
  292. let l:curHeaderLevel = s:GetLevelOfHeaderAtLine(l:curHeaderLineNumber)
  293. let l:curHeaderParentLineNumber = s:GetParentHeaderLineNumber()
  294. let l:nextHeaderSameLevelLineNumber = s:GetNextHeaderLineNumberAtLevel(l:curHeaderLevel, l:curHeaderLineNumber + 1)
  295. let l:noNextSibling = 0
  296. if l:nextHeaderSameLevelLineNumber == 0
  297. let l:noNextSibling = 1
  298. else
  299. let l:nextHeaderSameLevelParentLineNumber = s:GetParentHeaderLineNumber(l:nextHeaderSameLevelLineNumber)
  300. if l:curHeaderParentLineNumber == l:nextHeaderSameLevelParentLineNumber
  301. call cursor(l:nextHeaderSameLevelLineNumber, 1)
  302. else
  303. let l:noNextSibling = 1
  304. endif
  305. endif
  306. if l:noNextSibling
  307. echo 'no next sibling header'
  308. endif
  309. endfunction
  310. " Move cursor to previous sibling header.
  311. "
  312. " If there is no previous siblings, print a warning and do nothing.
  313. "
  314. function! s:MoveToPreviousSiblingHeader()
  315. let l:curHeaderLineNumber = s:GetHeaderLineNum()
  316. let l:curHeaderLevel = s:GetLevelOfHeaderAtLine(l:curHeaderLineNumber)
  317. let l:curHeaderParentLineNumber = s:GetParentHeaderLineNumber()
  318. let l:previousHeaderSameLevelLineNumber = s:GetPreviousHeaderLineNumberAtLevel(l:curHeaderLevel, l:curHeaderLineNumber - 1)
  319. let l:noPreviousSibling = 0
  320. if l:previousHeaderSameLevelLineNumber == 0
  321. let l:noPreviousSibling = 1
  322. else
  323. let l:previousHeaderSameLevelParentLineNumber = s:GetParentHeaderLineNumber(l:previousHeaderSameLevelLineNumber)
  324. if l:curHeaderParentLineNumber == l:previousHeaderSameLevelParentLineNumber
  325. call cursor(l:previousHeaderSameLevelLineNumber, 1)
  326. else
  327. let l:noPreviousSibling = 1
  328. endif
  329. endif
  330. if l:noPreviousSibling
  331. echo 'no previous sibling header'
  332. endif
  333. endfunction
  334. function! s:Toc(...)
  335. if a:0 > 0
  336. let l:window_type = a:1
  337. else
  338. let l:window_type = 'vertical'
  339. endif
  340. let l:cursor_line = line('.')
  341. let l:cursor_header = 0
  342. let l:header_list = s:GetHeaderList()
  343. let l:indented_header_list = []
  344. if len(l:header_list) == 0
  345. echom 'Toc: No headers.'
  346. return
  347. endif
  348. let l:header_max_len = 0
  349. let l:vim_markdown_toc_autofit = get(g:, 'vim_markdown_toc_autofit', 0)
  350. for h in l:header_list
  351. " set header number of the cursor position
  352. if l:cursor_header == 0
  353. let l:header_line = h.lnum
  354. if l:header_line == l:cursor_line
  355. let l:cursor_header = index(l:header_list, h) + 1
  356. elseif l:header_line > l:cursor_line
  357. let l:cursor_header = index(l:header_list, h)
  358. endif
  359. endif
  360. " indent header based on level
  361. let l:text = repeat(' ', h.level-1) . h.text
  362. " keep track of the longest header size (heading level + title)
  363. let l:total_len = strdisplaywidth(l:text)
  364. if l:total_len > l:header_max_len
  365. let l:header_max_len = l:total_len
  366. endif
  367. " append indented line to list
  368. let l:item = {'lnum': h.lnum, 'text': l:text, 'valid': 1, 'bufnr': h.bufnr, 'col': 1}
  369. let l:indented_header_list = l:indented_header_list + [l:item]
  370. endfor
  371. call setloclist(0, l:indented_header_list)
  372. if l:window_type ==# 'horizontal'
  373. lopen
  374. elseif l:window_type ==# 'vertical'
  375. vertical lopen
  376. " auto-fit toc window when possible to shrink it
  377. if (&columns/2) > l:header_max_len && l:vim_markdown_toc_autofit == 1
  378. " header_max_len + 1 space for first header + 3 spaces for line numbers
  379. execute 'vertical resize ' . (l:header_max_len + 1 + 3)
  380. else
  381. execute 'vertical resize ' . (&columns/2)
  382. endif
  383. elseif l:window_type ==# 'tab'
  384. tab lopen
  385. else
  386. lopen
  387. endif
  388. setlocal modifiable
  389. for i in range(1, line('$'))
  390. " this is the location-list data for the current item
  391. let d = getloclist(0)[i-1]
  392. call setline(i, d.text)
  393. endfor
  394. setlocal nomodified
  395. setlocal nomodifiable
  396. execute 'normal! ' . l:cursor_header . 'G'
  397. endfunction
  398. function! s:InsertToc(format, ...)
  399. if a:0 > 0
  400. if type(a:1) != type(0)
  401. echohl WarningMsg
  402. echomsg '[vim-markdown] Invalid argument, must be an integer >= 2.'
  403. echohl None
  404. return
  405. endif
  406. let l:max_level = a:1
  407. if l:max_level < 2
  408. echohl WarningMsg
  409. echomsg '[vim-markdown] Maximum level cannot be smaller than 2.'
  410. echohl None
  411. return
  412. endif
  413. else
  414. let l:max_level = 0
  415. endif
  416. let l:toc = []
  417. let l:header_list = s:GetHeaderList()
  418. if len(l:header_list) == 0
  419. echom 'InsertToc: No headers.'
  420. return
  421. endif
  422. if a:format ==# 'numbers'
  423. let l:h2_count = 0
  424. for header in l:header_list
  425. if header.level == 2
  426. let l:h2_count += 1
  427. endif
  428. endfor
  429. let l:max_h2_number_len = strlen(string(l:h2_count))
  430. else
  431. let l:max_h2_number_len = 0
  432. endif
  433. let l:h2_count = 0
  434. for header in l:header_list
  435. let l:level = header.level
  436. if l:level == 1
  437. " skip level-1 headers
  438. continue
  439. elseif l:max_level != 0 && l:level > l:max_level
  440. " skip unwanted levels
  441. continue
  442. elseif l:level == 2
  443. " list of level-2 headers can be bullets or numbers
  444. if a:format ==# 'bullets'
  445. let l:indent = ''
  446. let l:marker = '* '
  447. else
  448. let l:h2_count += 1
  449. let l:number_len = strlen(string(l:h2_count))
  450. let l:indent = repeat(' ', l:max_h2_number_len - l:number_len)
  451. let l:marker = l:h2_count . '. '
  452. endif
  453. else
  454. let l:indent = repeat(' ', l:max_h2_number_len + 2 * (l:level - 2))
  455. let l:marker = '* '
  456. endif
  457. let l:text = '[' . header.text . ']'
  458. let l:link = '(#' . substitute(tolower(header.text), '\v[ ]+', '-', 'g') . ')'
  459. let l:line = l:indent . l:marker . l:text . l:link
  460. let l:toc = l:toc + [l:line]
  461. endfor
  462. call append(line('.'), l:toc)
  463. endfunction
  464. " Convert Setex headers in range `line1 .. line2` to Atx.
  465. "
  466. " Return the number of conversions.
  467. "
  468. function! s:SetexToAtx(line1, line2)
  469. let l:originalNumLines = line('$')
  470. execute 'silent! ' . a:line1 . ',' . a:line2 . 'substitute/\v(.*\S.*)\n\=+$/# \1/'
  471. execute 'silent! ' . a:line1 . ',' . a:line2 . 'substitute/\v(.*\S.*)\n-+$/## \1/'
  472. return l:originalNumLines - line('$')
  473. endfunction
  474. " If `a:1` is 0, decrease the level of all headers in range `line1 .. line2`.
  475. "
  476. " Otherwise, increase the level. `a:1` defaults to `0`.
  477. "
  478. function! s:HeaderDecrease(line1, line2, ...)
  479. if a:0 > 0
  480. let l:increase = a:1
  481. else
  482. let l:increase = 0
  483. endif
  484. if l:increase
  485. let l:forbiddenLevel = 6
  486. let l:replaceLevels = [5, 1]
  487. let l:levelDelta = 1
  488. else
  489. let l:forbiddenLevel = 1
  490. let l:replaceLevels = [2, 6]
  491. let l:levelDelta = -1
  492. endif
  493. for l:line in range(a:line1, a:line2)
  494. if join(getline(l:line, l:line + 1), "\n") =~ s:levelRegexpDict[l:forbiddenLevel]
  495. echomsg 'There is an h' . l:forbiddenLevel . ' at line ' . l:line . '. Aborting.'
  496. return
  497. endif
  498. endfor
  499. let l:numSubstitutions = s:SetexToAtx(a:line1, a:line2)
  500. let l:flags = (&gdefault ? '' : 'g')
  501. for l:level in range(replaceLevels[0], replaceLevels[1], -l:levelDelta)
  502. execute 'silent! ' . a:line1 . ',' . (a:line2 - l:numSubstitutions) . 'substitute/' . s:levelRegexpDict[l:level] . '/' . repeat('#', l:level + l:levelDelta) . '/' . l:flags
  503. endfor
  504. endfunction
  505. " Format table under cursor.
  506. "
  507. " Depends on Tabularize.
  508. "
  509. function! s:TableFormat()
  510. let l:pos = getpos('.')
  511. normal! {
  512. " Search instead of `normal! j` because of the table at beginning of file edge case.
  513. call search('|')
  514. normal! j
  515. " Remove everything that is not a pipe, colon or hyphen next to a colon othewise
  516. " well formated tables would grow because of addition of 2 spaces on the separator
  517. " line by Tabularize /|.
  518. let l:flags = (&gdefault ? '' : 'g')
  519. execute 's/\(:\@<!-:\@!\|[^|:-]\)//e' . l:flags
  520. execute 's/--/-/e' . l:flags
  521. Tabularize /|
  522. " Move colons for alignment to left or right side of the cell.
  523. execute 's/:\( \+\)|/\1:|/e' . l:flags
  524. execute 's/|\( \+\):/|:\1/e' . l:flags
  525. execute 's/|:\?\zs[ -]\+\ze:\?|/\=repeat("-", len(submatch(0)))/' . l:flags
  526. call setpos('.', l:pos)
  527. endfunction
  528. " Wrapper to do move commands in visual mode.
  529. "
  530. function! s:VisMove(f)
  531. norm! gv
  532. call function(a:f)()
  533. endfunction
  534. " Map in both normal and visual modes.
  535. "
  536. function! s:MapNormVis(rhs,lhs)
  537. execute 'nn <buffer><silent> ' . a:rhs . ' :call ' . a:lhs . '()<cr>'
  538. execute 'vn <buffer><silent> ' . a:rhs . ' <esc>:call <sid>VisMove(''' . a:lhs . ''')<cr>'
  539. endfunction
  540. " Parameters:
  541. "
  542. " - step +1 for right, -1 for left
  543. "
  544. " TODO: multiple lines.
  545. "
  546. function! s:FindCornerOfSyntax(lnum, col, step)
  547. let l:col = a:col
  548. let l:syn = synIDattr(synID(a:lnum, l:col, 1), 'name')
  549. while synIDattr(synID(a:lnum, l:col, 1), 'name') ==# l:syn
  550. let l:col += a:step
  551. endwhile
  552. return l:col - a:step
  553. endfunction
  554. " Return the next position of the given syntax name,
  555. " inclusive on the given position.
  556. "
  557. " TODO: multiple lines
  558. "
  559. function! s:FindNextSyntax(lnum, col, name)
  560. let l:col = a:col
  561. let l:step = 1
  562. while synIDattr(synID(a:lnum, l:col, 1), 'name') !=# a:name
  563. let l:col += l:step
  564. endwhile
  565. return [a:lnum, l:col]
  566. endfunction
  567. function! s:FindCornersOfSyntax(lnum, col)
  568. return [<sid>FindLeftOfSyntax(a:lnum, a:col), <sid>FindRightOfSyntax(a:lnum, a:col)]
  569. endfunction
  570. function! s:FindRightOfSyntax(lnum, col)
  571. return <sid>FindCornerOfSyntax(a:lnum, a:col, 1)
  572. endfunction
  573. function! s:FindLeftOfSyntax(lnum, col)
  574. return <sid>FindCornerOfSyntax(a:lnum, a:col, -1)
  575. endfunction
  576. " Returns:
  577. "
  578. " - a string with the the URL for the link under the cursor
  579. " - an empty string if the cursor is not on a link
  580. "
  581. " TODO
  582. "
  583. " - multiline support
  584. " - give an error if the separator does is not on a link
  585. "
  586. function! s:Markdown_GetUrlForPosition(lnum, col)
  587. let l:lnum = a:lnum
  588. let l:col = a:col
  589. let l:syn = synIDattr(synID(l:lnum, l:col, 1), 'name')
  590. if l:syn ==# 'mkdInlineURL' || l:syn ==# 'mkdURL' || l:syn ==# 'mkdLinkDefTarget'
  591. " Do nothing.
  592. elseif l:syn ==# 'mkdLink'
  593. let [l:lnum, l:col] = <sid>FindNextSyntax(l:lnum, l:col, 'mkdURL')
  594. let l:syn = 'mkdURL'
  595. elseif l:syn ==# 'mkdDelimiter'
  596. let l:line = getline(l:lnum)
  597. let l:char = l:line[col - 1]
  598. if l:char ==# '<'
  599. let l:col += 1
  600. elseif l:char ==# '>' || l:char ==# ')'
  601. let l:col -= 1
  602. elseif l:char ==# '[' || l:char ==# ']' || l:char ==# '('
  603. let [l:lnum, l:col] = <sid>FindNextSyntax(l:lnum, l:col, 'mkdURL')
  604. else
  605. return ''
  606. endif
  607. else
  608. return ''
  609. endif
  610. let [l:left, l:right] = <sid>FindCornersOfSyntax(l:lnum, l:col)
  611. return getline(l:lnum)[l:left - 1 : l:right - 1]
  612. endfunction
  613. " Front end for GetUrlForPosition.
  614. "
  615. function! s:OpenUrlUnderCursor()
  616. let l:url = s:Markdown_GetUrlForPosition(line('.'), col('.'))
  617. if l:url !=# ''
  618. call s:VersionAwareNetrwBrowseX(l:url)
  619. else
  620. echomsg 'The cursor is not on a link.'
  621. endif
  622. endfunction
  623. " We need a definition guard because we invoke 'edit' which will reload this
  624. " script while this function is running. We must not replace it.
  625. if !exists('*s:EditUrlUnderCursor')
  626. function s:EditUrlUnderCursor()
  627. let l:editmethod = ''
  628. " determine how to open the linked file (split, tab, etc)
  629. if exists('g:vim_markdown_edit_url_in')
  630. if g:vim_markdown_edit_url_in ==# 'tab'
  631. let l:editmethod = 'tabnew'
  632. elseif g:vim_markdown_edit_url_in ==# 'vsplit'
  633. let l:editmethod = 'vsp'
  634. elseif g:vim_markdown_edit_url_in ==# 'hsplit'
  635. let l:editmethod = 'sp'
  636. else
  637. let l:editmethod = 'edit'
  638. endif
  639. else
  640. " default to current buffer
  641. let l:editmethod = 'edit'
  642. endif
  643. let l:url = s:Markdown_GetUrlForPosition(line('.'), col('.'))
  644. if l:url !=# ''
  645. if get(g:, 'vim_markdown_autowrite', 0)
  646. write
  647. endif
  648. let l:anchor = ''
  649. if get(g:, 'vim_markdown_follow_anchor', 0)
  650. let l:parts = split(l:url, '#', 1)
  651. if len(l:parts) == 2
  652. let [l:url, l:anchor] = parts
  653. let l:anchorexpr = get(g:, 'vim_markdown_anchorexpr', '')
  654. if l:anchorexpr !=# ''
  655. let l:anchor = eval(substitute(
  656. \ l:anchorexpr, 'v:anchor',
  657. \ escape('"'.l:anchor.'"', '"'), ''))
  658. endif
  659. endif
  660. endif
  661. if l:url !=# ''
  662. let l:ext = ''
  663. if get(g:, 'vim_markdown_no_extensions_in_markdown', 0)
  664. " use another file extension if preferred
  665. if exists('g:vim_markdown_auto_extension_ext')
  666. let l:ext = '.'.g:vim_markdown_auto_extension_ext
  667. else
  668. let l:ext = '.md'
  669. endif
  670. endif
  671. let l:url = fnameescape(fnamemodify(expand('%:h').'/'.l:url.l:ext, ':.'))
  672. execute l:editmethod l:url
  673. endif
  674. if l:anchor !=# ''
  675. silent! execute '/'.l:anchor
  676. endif
  677. else
  678. execute l:editmethod . ' <cfile>'
  679. endif
  680. endfunction
  681. endif
  682. function! s:VersionAwareNetrwBrowseX(url)
  683. if has('patch-7.4.567')
  684. call netrw#BrowseX(a:url, 0)
  685. else
  686. call netrw#NetrwBrowseX(a:url, 0)
  687. endif
  688. endf
  689. function! s:MapNotHasmapto(lhs, rhs)
  690. if !hasmapto('<Plug>' . a:rhs)
  691. execute 'nmap <buffer>' . a:lhs . ' <Plug>' . a:rhs
  692. execute 'vmap <buffer>' . a:lhs . ' <Plug>' . a:rhs
  693. endif
  694. endfunction
  695. call <sid>MapNormVis('<Plug>Markdown_MoveToNextHeader', '<sid>MoveToNextHeader')
  696. call <sid>MapNormVis('<Plug>Markdown_MoveToPreviousHeader', '<sid>MoveToPreviousHeader')
  697. call <sid>MapNormVis('<Plug>Markdown_MoveToNextSiblingHeader', '<sid>MoveToNextSiblingHeader')
  698. call <sid>MapNormVis('<Plug>Markdown_MoveToPreviousSiblingHeader', '<sid>MoveToPreviousSiblingHeader')
  699. call <sid>MapNormVis('<Plug>Markdown_MoveToParentHeader', '<sid>MoveToParentHeader')
  700. call <sid>MapNormVis('<Plug>Markdown_MoveToCurHeader', '<sid>MoveToCurHeader')
  701. nnoremap <Plug>Markdown_OpenUrlUnderCursor :call <sid>OpenUrlUnderCursor()<cr>
  702. nnoremap <Plug>Markdown_EditUrlUnderCursor :call <sid>EditUrlUnderCursor()<cr>
  703. if !get(g:, 'vim_markdown_no_default_key_mappings', 0)
  704. call <sid>MapNotHasmapto(']]', 'Markdown_MoveToNextHeader')
  705. call <sid>MapNotHasmapto('[[', 'Markdown_MoveToPreviousHeader')
  706. call <sid>MapNotHasmapto('][', 'Markdown_MoveToNextSiblingHeader')
  707. call <sid>MapNotHasmapto('[]', 'Markdown_MoveToPreviousSiblingHeader')
  708. call <sid>MapNotHasmapto(']u', 'Markdown_MoveToParentHeader')
  709. call <sid>MapNotHasmapto(']h', 'Markdown_MoveToCurHeader')
  710. call <sid>MapNotHasmapto('gx', 'Markdown_OpenUrlUnderCursor')
  711. call <sid>MapNotHasmapto('ge', 'Markdown_EditUrlUnderCursor')
  712. endif
  713. command! -buffer -range=% HeaderDecrease call s:HeaderDecrease(<line1>, <line2>)
  714. command! -buffer -range=% HeaderIncrease call s:HeaderDecrease(<line1>, <line2>, 1)
  715. command! -buffer -range=% SetexToAtx call s:SetexToAtx(<line1>, <line2>)
  716. command! -buffer TableFormat call s:TableFormat()
  717. command! -buffer Toc call s:Toc()
  718. command! -buffer Toch call s:Toc('horizontal')
  719. command! -buffer Tocv call s:Toc('vertical')
  720. command! -buffer Toct call s:Toc('tab')
  721. command! -buffer -nargs=? InsertToc call s:InsertToc('bullets', <args>)
  722. command! -buffer -nargs=? InsertNToc call s:InsertToc('numbers', <args>)
  723. " Heavily based on vim-notes - http://peterodding.com/code/vim/notes/
  724. if exists('g:vim_markdown_fenced_languages')
  725. let s:filetype_dict = {}
  726. for s:filetype in g:vim_markdown_fenced_languages
  727. let key = matchstr(s:filetype, '[^=]*')
  728. let val = matchstr(s:filetype, '[^=]*$')
  729. let s:filetype_dict[key] = val
  730. endfor
  731. else
  732. let s:filetype_dict = {
  733. \ 'c++': 'cpp',
  734. \ 'viml': 'vim',
  735. \ 'bash': 'sh',
  736. \ 'ini': 'dosini'
  737. \ }
  738. endif
  739. function! s:MarkdownHighlightSources(force)
  740. " Syntax highlight source code embedded in notes.
  741. " Look for code blocks in the current file
  742. let filetypes = {}
  743. for line in getline(1, '$')
  744. let ft = matchstr(line, '\(`\{3,}\|\~\{3,}\)\s*\zs[0-9A-Za-z_+-]*\ze.*')
  745. if !empty(ft) && ft !~# '^\d*$' | let filetypes[ft] = 1 | endif
  746. endfor
  747. if !exists('b:mkd_known_filetypes')
  748. let b:mkd_known_filetypes = {}
  749. endif
  750. if !exists('b:mkd_included_filetypes')
  751. " set syntax file name included
  752. let b:mkd_included_filetypes = {}
  753. endif
  754. if !a:force && (b:mkd_known_filetypes == filetypes || empty(filetypes))
  755. return
  756. endif
  757. " Now we're ready to actually highlight the code blocks.
  758. let startgroup = 'mkdCodeStart'
  759. let endgroup = 'mkdCodeEnd'
  760. for ft in keys(filetypes)
  761. if a:force || !has_key(b:mkd_known_filetypes, ft)
  762. if has_key(s:filetype_dict, ft)
  763. let filetype = s:filetype_dict[ft]
  764. else
  765. let filetype = ft
  766. endif
  767. let group = 'mkdSnippet' . toupper(substitute(filetype, '[+-]', '_', 'g'))
  768. if !has_key(b:mkd_included_filetypes, filetype)
  769. let include = s:SyntaxInclude(filetype)
  770. let b:mkd_included_filetypes[filetype] = 1
  771. else
  772. let include = '@' . toupper(filetype)
  773. endif
  774. let command_backtick = 'syntax region %s matchgroup=%s start="^\s*`\{3,}\s*%s.*$" matchgroup=%s end="\s*`\{3,}$" keepend contains=%s%s'
  775. let command_tilde = 'syntax region %s matchgroup=%s start="^\s*\~\{3,}\s*%s.*$" matchgroup=%s end="\s*\~\{3,}$" keepend contains=%s%s'
  776. 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' : '')
  777. 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' : '')
  778. execute printf('syntax cluster mkdNonListItem add=%s', group)
  779. let b:mkd_known_filetypes[ft] = 1
  780. endif
  781. endfor
  782. endfunction
  783. function! s:SyntaxInclude(filetype)
  784. " Include the syntax highlighting of another {filetype}.
  785. let grouplistname = '@' . toupper(a:filetype)
  786. " Unset the name of the current syntax while including the other syntax
  787. " because some syntax scripts do nothing when "b:current_syntax" is set
  788. if exists('b:current_syntax')
  789. let syntax_save = b:current_syntax
  790. unlet b:current_syntax
  791. endif
  792. try
  793. execute 'syntax include' grouplistname 'syntax/' . a:filetype . '.vim'
  794. execute 'syntax include' grouplistname 'after/syntax/' . a:filetype . '.vim'
  795. catch /E484/
  796. " Ignore missing scripts
  797. endtry
  798. " Restore the name of the current syntax
  799. if exists('syntax_save')
  800. let b:current_syntax = syntax_save
  801. elseif exists('b:current_syntax')
  802. unlet b:current_syntax
  803. endif
  804. return grouplistname
  805. endfunction
  806. function! s:MarkdownRefreshSyntax(force)
  807. " Use != to compare &syntax's value to use the same logic run on
  808. " $VIMRUNTIME/syntax/synload.vim.
  809. "
  810. " vint: next-line -ProhibitEqualTildeOperator
  811. if &filetype =~# 'markdown' && line('$') > 1 && &syntax != 'OFF'
  812. call s:MarkdownHighlightSources(a:force)
  813. endif
  814. endfunction
  815. function! s:MarkdownClearSyntaxVariables()
  816. if &filetype =~# 'markdown'
  817. unlet! b:mkd_included_filetypes
  818. endif
  819. endfunction
  820. augroup Mkd
  821. " These autocmd calling s:MarkdownRefreshSyntax need to be kept in sync with
  822. " the autocmds calling s:MarkdownSetupFolding in after/ftplugin/markdown.vim.
  823. autocmd! * <buffer>
  824. autocmd BufWinEnter <buffer> call s:MarkdownRefreshSyntax(1)
  825. autocmd BufUnload <buffer> call s:MarkdownClearSyntaxVariables()
  826. autocmd BufWritePost <buffer> call s:MarkdownRefreshSyntax(0)
  827. autocmd InsertEnter,InsertLeave <buffer> call s:MarkdownRefreshSyntax(0)
  828. autocmd CursorHold,CursorHoldI <buffer> call s:MarkdownRefreshSyntax(0)
  829. augroup END