vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

rmd.vim (11060B)


      1 " Language: Markdown with chunks of R, Python and other languages
      2 " Maintainer: This runtime file is looking for a new maintainer.
      3 " Former Maintainer: Jakson Alves de Aquino <jalvesaq@gmail.com>
      4 " Former Repository: https://github.com/jalvesaq/R-Vim-runtime
      5 " Last Change: 2023 Dec 24  07:21AM
      6 "   2024 Feb 19 by Vim project (announce adoption)
      7 "   2026 Sep 29 by Vim project (fix typo in code block delimiter pattern)
      8 "   2026 Oct 11 by Vim project (fix code execution via fenced pattern)
      9 "
     10 "   For highlighting pandoc extensions to markdown like citations and TeX and
     11 "   many other advanced features like folding of markdown sections, it is
     12 "   recommended to install the vim-pandoc filetype plugin as well as the
     13 "   vim-pandoc-syntax filetype plugin from https://github.com/vim-pandoc.
     14 
     15 
     16 if exists("b:current_syntax")
     17   finish
     18 endif
     19 
     20 let s:cpo_save = &cpo
     21 set cpo&vim
     22 
     23 let g:rmd_include_latex = get(g:, 'rmd_include_latex', 1)
     24 if g:rmd_include_latex == 0 || g:rmd_include_latex == 1
     25   let b:rmd_has_LaTeX = v:false
     26 elseif g:rmd_include_latex == 2
     27   let b:rmd_has_LaTeX = v:true
     28 endif
     29 
     30 " Highlight the header of the chunks as R code
     31 let g:rmd_syn_hl_chunk = get(g:, 'rmd_syn_hl_chunk', 0)
     32 
     33 " Pandoc-syntax has more features, but it is slower.
     34 " https://github.com/vim-pandoc/vim-pandoc-syntax
     35 
     36 " Don't waste time loading syntax that will be discarded:
     37 let s:save_pandoc_lngs = get(g:, 'pandoc#syntax#codeblocks#embeds#langs', [])
     38 let g:pandoc#syntax#codeblocks#embeds#langs = []
     39 
     40 let g:rmd_dynamic_fenced_languages = get(g:, 'rmd_dynamic_fenced_languages', v:true)
     41 
     42 " Step_1: Source pandoc.vim if it is installed:
     43 runtime syntax/pandoc.vim
     44 if exists("b:current_syntax")
     45   if hlexists('pandocDelimitedCodeBlock')
     46     syn clear pandocDelimitedCodeBlock
     47   endif
     48 
     49   if len(s:save_pandoc_lngs) > 0 && !exists('g:rmd_fenced_languages')
     50     let g:rmd_fenced_languages = deepcopy(s:save_pandoc_lngs)
     51   endif
     52 
     53   " Recognize inline R code
     54   syn region rmdrInline matchgroup=rmdInlineDelim start="`r "  end="`" contains=@Rmdr containedin=pandocLaTeXRegion,yamlFlowString keepend
     55 else
     56   " Step_2: Source markdown.vim if pandoc.vim is not installed
     57 
     58   " Configuration if not using pandoc syntax:
     59   " Add syntax highlighting of YAML header
     60   let g:rmd_syn_hl_yaml = get(g:, 'rmd_syn_hl_yaml', 1)
     61   " Add syntax highlighting of citation keys
     62   let g:rmd_syn_hl_citations = get(g:, 'rmd_syn_hl_citations', 1)
     63 
     64   " R chunks will not be highlighted by syntax/markdown because their headers
     65   " follow a non standard pattern: "```{lang" instead of "^```lang".
     66   " Make a copy of g:markdown_fenced_languages to highlight the chunks later:
     67   if exists('g:markdown_fenced_languages') && !exists('g:rmd_fenced_languages')
     68     let g:rmd_fenced_languages = deepcopy(g:markdown_fenced_languages)
     69   endif
     70 
     71   if exists('g:markdown_fenced_languages') && len(g:markdown_fenced_languages) > 0
     72     let s:save_mfl = deepcopy(g:markdown_fenced_languages)
     73   endif
     74   " Don't waste time loading syntax that will be discarded:
     75   let g:markdown_fenced_languages = []
     76   runtime syntax/markdown.vim
     77   if exists('s:save_mfl') > 0
     78     let g:markdown_fenced_languages = deepcopy(s:save_mfl)
     79     unlet s:save_mfl
     80   endif
     81   syn region rmdrInline matchgroup=rmdInlineDelim start="`r "  end="`" contains=@Rmdr keepend
     82 
     83   " Step_2a: Add highlighting for both YAML and citations which are pandoc
     84   " specific, but also used in Rmd files
     85 
     86   " You don't need this if either your markdown/syntax.vim already highlights
     87   " the YAML header or you are writing standard markdown
     88   if g:rmd_syn_hl_yaml
     89     " Basic highlighting of YAML header
     90     syn match rmdYamlFieldTtl /^\s*\zs\w\%(-\|\w\)*\ze:/ contained
     91     syn match rmdYamlFieldTtl /^\s*-\s*\zs\w\%(-\|\w\)*\ze:/ contained
     92     syn region yamlFlowString matchgroup=yamlFlowStringDelimiter start='"' skip='\\"' end='"' contains=yamlEscape,rmdrInline contained
     93     syn region yamlFlowString matchgroup=yamlFlowStringDelimiter start="'" skip="''"  end="'" contains=yamlSingleEscape,rmdrInline contained
     94     syn match  yamlEscape contained '\\\%([\\"abefnrtv\^0_ NLP\n]\|x\x\x\|u\x\{4}\|U\x\{8}\)'
     95     syn match  yamlSingleEscape contained "''"
     96     syn match yamlComment /#.*/ contained
     97     " A second colon is a syntax error, unless within a string or following !expr
     98     syn match yamlColonError /:\s*[^'^"^!]*:/ contained
     99     if &filetype == 'quarto'
    100       syn region pandocYAMLHeader matchgroup=rmdYamlBlockDelim start=/\%(\%^\|\_^\s*\n\)\@<=\_^-\{3}\ze\n.\+/ end=/^---$/ keepend contains=rmdYamlFieldTtl,yamlFlowString,yamlComment,yamlColonError
    101     else
    102       syn region pandocYAMLHeader matchgroup=rmdYamlBlockDelim start=/\%(\%^\|\_^\s*\n\)\@<=\_^-\{3}\ze\n.\+/ end=/^\([-.]\)\1\{2}$/ keepend contains=rmdYamlFieldTtl,yamlFlowString,yamlComment,yamlColonError
    103     endif
    104     hi def link rmdYamlBlockDelim Delimiter
    105     hi def link rmdYamlFieldTtl Identifier
    106     hi def link yamlFlowString String
    107     hi def link yamlComment Comment
    108     hi def link yamlColonError Error
    109   endif
    110 
    111   " Conceal char for manual line break
    112   if &encoding ==# 'utf-8'
    113     syn match rmdNewLine '  $' conceal cchar=↵
    114   endif
    115 
    116   " You don't need this if either your markdown/syntax.vim already highlights
    117   " citations or you are writing standard markdown
    118   if g:rmd_syn_hl_citations
    119     " From vim-pandoc-syntax
    120     " parenthetical citations
    121     syn match pandocPCite /\^\@<!\[[^\[\]]\{-}-\{0,1}@[[:alnum:]_][[:alnum:]à-öø-ÿÀ-ÖØ-ß_:.#$%&\-+?<>~\/]*.\{-}\]/ contains=pandocEmphasis,pandocStrong,pandocLatex,pandocCiteKey,@Spell,pandocAmpersandEscape display
    122     " in-text citations with location
    123     syn match pandocICite /@[[:alnum:]_][[:alnum:]à-öø-ÿÀ-ÖØ-ß_:.#$%&\-+?<>~\/]*\s\[.\{-1,}\]/ contains=pandocCiteKey,@Spell display
    124     " cite keys
    125     syn match pandocCiteKey /\(-\=@[[:alnum:]_][[:alnum:]à-öø-ÿÀ-ÖØ-ß_:.#$%&\-+?<>~\/]*\)/ containedin=pandocPCite,pandocICite contains=@NoSpell display
    126     syn match pandocCiteAnchor /[-@]/ contained containedin=pandocCiteKey display
    127     syn match pandocCiteLocator /[\[\]]/ contained containedin=pandocPCite,pandocICite
    128     hi def link pandocPCite Operator
    129     hi def link pandocICite Operator
    130     hi def link pandocCiteKey Label
    131     hi def link pandocCiteAnchor Operator
    132     hi def link pandocCiteLocator Operator
    133   endif
    134 endif
    135 
    136 " Step_3: Highlight code blocks.
    137 
    138 syn region rmdCodeBlock matchgroup=rmdCodeDelim start="^\s*```\s*{.*}$" matchgroup=rmdCodeDelim end="^\s*```\ze\s*$" keepend
    139 syn region rmdCodeBlock matchgroup=rmdCodeDelim start="^\s*```.\+$" matchgroup=rmdCodeDelim end="^\s*```\ze\s*$" keepend
    140 hi link rmdCodeBlock Special
    141 
    142 " Now highlight chunks:
    143 syn region knitrBodyOptions start='^#| ' end='$' contained  containedin=rComment,pythonComment contains=knitrBodyVar,knitrBodyValue transparent
    144 syn match knitrBodyValue ': \zs.*\ze$' keepend contained containedin=knitrBodyOptions
    145 syn match knitrBodyVar '| \zs\S\{-}\ze:' contained containedin=knitrBodyOptions
    146 
    147 let g:rmd_fenced_languages = get(g:, 'rmd_fenced_languages', ['r'])
    148 
    149 let s:no_syntax_vim = []
    150 function s:IncludeLanguage(lng)
    151   if a:lng =~ '='
    152     let ftpy = substitute(a:lng, '.*=', '', '')
    153     let lnm = substitute(a:lng, '=.*', '', '')
    154   else
    155     let ftpy = a:lng
    156     let lnm  = a:lng
    157   endif
    158   if index(s:no_syntax_vim, ftpy) >= 0
    159     return
    160   endif
    161   if len(globpath(&rtp, "syntax/" . ftpy . ".vim"))
    162     unlet! b:current_syntax
    163     exe 'syn include @Rmd'.lnm.' syntax/'.ftpy.'.vim'
    164     let b:current_syntax = "rmd"
    165     if g:rmd_syn_hl_chunk
    166       exe 'syn match knitrChunkDelim /```\s*{\s*'.lnm.'/ contained containedin=knitrChunkBrace contains=knitrChunkLabel'
    167       exe 'syn match knitrChunkLabelDelim /```\s*{\s*'.lnm.',\=\s*[-[:alnum:]]\{-1,}[,}]/ contained containedin=knitrChunkBrace'
    168       syn match knitrChunkDelim /}\s*$/ contained containedin=knitrChunkBrace
    169       exe 'syn match knitrChunkBrace /```\s*{\s*'.lnm.'.*$/ contained containedin=rmd'.lnm.'Chunk contains=knitrChunkDelim,knitrChunkLabelDelim,@Rmd'.lnm
    170       exe 'syn region rmd'.lnm.'Chunk start="^\s*```\s*{\s*=\?'.lnm.'\>.*$" matchgroup=rmdCodeDelim end="^\s*```\ze\s*$" keepend contains=knitrChunkBrace,@Rmd'.lnm
    171 
    172       hi link knitrChunkLabel Identifier
    173       hi link knitrChunkDelim rmdCodeDelim
    174       hi link knitrChunkLabelDelim rmdCodeDelim
    175     else
    176       exe 'syn region rmd'.lnm.'Chunk matchgroup=rmdCodeDelim start="^\s*```\s*{\s*=\?'.lnm.'\>.*$" matchgroup=rmdCodeDelim end="^\s*```\ze\s*$" keepend contains=@Rmd'.lnm
    177     endif
    178   else
    179     " Avoid the cost of running globpath() whenever the buffer is saved
    180     let s:no_syntax_vim += [ftpy]
    181   endif
    182 endfunction
    183 
    184 for s:type in g:rmd_fenced_languages
    185   call s:IncludeLanguage(s:type)
    186 endfor
    187 unlet! s:type
    188 
    189 let s:LaTeX_included = v:false
    190 function s:IncludeLaTeX()
    191   let s:LaTeX_included = v:true
    192   unlet! b:current_syntax
    193   syn include @RmdLaTeX syntax/tex.vim
    194   " From vim-pandoc-syntax
    195   syn region rmdLaTeXInlineMath start=/\v\\@<!\$\S@=/ end=/\v\\@<!\$\d@!/ keepend contains=@RmdLaTeX
    196   syn match rmdLaTeXCmd /\\[[:alpha:]]\+\(\({.\{-}}\)\=\(\[.\{-}\]\)\=\)*/ contains=@RmdLaTeX
    197   syn region rmdLaTeX start='\$\$'  end='\$\$' keepend contains=@RmdLaTeX
    198   syn region rmdLaTeX start=/\\begin{\z(.\{-}\)}/ end=/\\end{\z1}/ keepend contains=@RmdLaTeX
    199 endfunction
    200 
    201 function s:CheckRmdFencedLanguages()
    202   let alines = getline(1, '$')
    203   let pat = '^\w\+'
    204   call filter(alines, "v:val =~ '^```{'")
    205   call map(alines, "substitute(v:val, '^```{', '', '')")
    206   call map(alines, "matchstr(v:val, pat)")
    207   for tpy in alines
    208     if len(tpy) == 0
    209       continue
    210     endif
    211     let has_lng = 0
    212     for lng in g:rmd_fenced_languages
    213       if tpy == lng
    214         let has_lng = 1
    215         continue
    216       endif
    217     endfor
    218     if has_lng == 0
    219       let g:rmd_fenced_languages += [tpy]
    220       call s:IncludeLanguage(tpy)
    221     endif
    222   endfor
    223 
    224   if hlexists('pandocLaTeXCommand')
    225     return
    226   endif
    227   if g:rmd_include_latex
    228     if !b:rmd_has_LaTeX && (search('\$\$', 'wn') > 0 ||
    229           \ search('\\begin{', 'wn') > 0) ||
    230           \ search('\\[[:alpha:]]\+', 'wn') ||
    231           \ search('\$[^\$]\+\$', 'wn')
    232       let b:rmd_has_LaTeX = v:true
    233     endif
    234     if b:rmd_has_LaTeX && !s:LaTeX_included
    235       call s:IncludeLaTeX()
    236     endif
    237   endif
    238 endfunction
    239 
    240 if g:rmd_dynamic_fenced_languages
    241   call s:CheckRmdFencedLanguages()
    242   augroup RmdSyntax
    243     autocmd!
    244     autocmd BufWritePost <buffer> call s:CheckRmdFencedLanguages()
    245   augroup END
    246 endif
    247 
    248 " Step_4: Highlight code recognized by pandoc but not defined in pandoc.vim yet:
    249 syn match pandocDivBegin '^:::\+ {.\{-}}' contains=pandocHeaderAttr
    250 syn match pandocDivEnd '^:::\+$'
    251 
    252 hi def link knitrBodyVar PreProc
    253 hi def link knitrBodyValue Constant
    254 hi def link knitrBodyOptions rComment
    255 hi def link pandocDivBegin Delimiter
    256 hi def link pandocDivEnd Delimiter
    257 hi def link rmdInlineDelim Delimiter
    258 hi def link rmdCodeDelim Delimiter
    259 
    260 if len(s:save_pandoc_lngs)
    261   let g:pandoc#syntax#codeblocks#embeds#langs = s:save_pandoc_lngs
    262 endif
    263 unlet s:save_pandoc_lngs
    264 let &cpo = s:cpo_save
    265 unlet s:cpo_save
    266 
    267 syntax iskeyword clear
    268 
    269 let b:current_syntax = "rmd"
    270 
    271 " vim: ts=8 sw=2