vim

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

rust.vim (17050B)


      1 " Description: Helper functions for Rust commands/mappings
      2 " Last Modified: 2023-09-11
      3 " 2026 May 20 by Vim project: use correct shellescape() with ! command
      4 " For bugs, patches and license go to https://github.com/rust-lang/rust.vim
      5 
      6 function! rust#Load()
      7     " Utility call to get this script loaded, for debugging
      8 endfunction
      9 
     10 function! rust#GetConfigVar(name, default)
     11     " Local buffer variable with same name takes predeence over global
     12     if has_key(b:, a:name)
     13         return get(b:, a:name)
     14     endif
     15     if has_key(g:, a:name)
     16         return get(g:, a:name)
     17     endif
     18     return a:default
     19 endfunction
     20 
     21 " Include expression {{{1
     22 
     23 function! rust#IncludeExpr(fname) abort
     24     " Remove leading 'crate::' to deal with 2018 edition style 'use'
     25     " statements
     26     let l:fname = substitute(a:fname, '^crate::', '', '')
     27 
     28     " Remove trailing colons arising from lines like
     29     "
     30     "     use foo::{Bar, Baz};
     31     let l:fname = substitute(l:fname, ':\+$', '', '')
     32 
     33     " Replace '::' with '/'
     34     let l:fname = substitute(l:fname, '::', '/', 'g')
     35 
     36     " When we have
     37     "
     38     "    use foo::bar::baz;
     39     "
     40     " we can't tell whether baz is a module or a function; and we can't tell
     41     " which modules correspond to files.
     42     "
     43     " So we work our way up, trying
     44     "
     45     "     foo/bar/baz.rs
     46     "     foo/bar.rs
     47     "     foo.rs
     48     while l:fname !=# '.'
     49         let l:path = findfile(l:fname)
     50         if !empty(l:path)
     51             return l:fname
     52         endif
     53         let l:fname = fnamemodify(l:fname, ':h')
     54     endwhile
     55     return l:fname
     56 endfunction
     57 
     58 " Jump {{{1
     59 
     60 function! rust#Jump(mode, function) range
     61     let cnt = v:count1
     62     normal! m'
     63     if a:mode ==# 'v'
     64         norm! gv
     65     endif
     66     let foldenable = &foldenable
     67     set nofoldenable
     68     while cnt > 0
     69         execute "call <SID>Jump_" . a:function . "()"
     70         let cnt = cnt - 1
     71     endwhile
     72     let &foldenable = foldenable
     73 endfunction
     74 
     75 function! s:Jump_Back()
     76     call search('{', 'b')
     77     keepjumps normal! w99[{
     78 endfunction
     79 
     80 function! s:Jump_Forward()
     81     normal! j0
     82     call search('{', 'b')
     83     keepjumps normal! w99[{%
     84     call search('{')
     85 endfunction
     86 
     87 " Run {{{1
     88 
     89 function! rust#Run(bang, args)
     90     let args = s:ShellTokenize(a:args)
     91     if a:bang
     92         let idx = index(l:args, '--')
     93         if idx != -1
     94             let rustc_args = idx == 0 ? [] : l:args[:idx-1]
     95             let args = l:args[idx+1:]
     96         else
     97             let rustc_args = l:args
     98             let args = []
     99         endif
    100     else
    101         let rustc_args = []
    102     endif
    103 
    104     let b:rust_last_rustc_args = l:rustc_args
    105     let b:rust_last_args = l:args
    106 
    107     call s:WithPath(function("s:Run"), rustc_args, args)
    108 endfunction
    109 
    110 function! s:Run(dict, rustc_args, args)
    111     let exepath = a:dict.tmpdir.'/'.fnamemodify(a:dict.path, ':t:r')
    112     if has('win32')
    113         let exepath .= '.exe'
    114     endif
    115 
    116     let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
    117     let rustc_args = [relpath, '-o', exepath] + a:rustc_args
    118 
    119     let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
    120 
    121     let pwd = a:dict.istemp ? a:dict.tmpdir : ''
    122     let output = s:system(pwd, shellescape(rustc) . " " . join(map(rustc_args, 'shellescape(v:val)')))
    123     if output !=# ''
    124         echohl WarningMsg
    125         echo output
    126         echohl None
    127     endif
    128     if !v:shell_error
    129         exe '!' . shellescape(exepath,1) . " " . join(map(a:args, 'shellescape(v:val,1)'))
    130     endif
    131 endfunction
    132 
    133 " Expand {{{1
    134 
    135 function! rust#Expand(bang, args)
    136     let args = s:ShellTokenize(a:args)
    137     if a:bang && !empty(l:args)
    138         let pretty = remove(l:args, 0)
    139     else
    140         let pretty = "expanded"
    141     endif
    142     call s:WithPath(function("s:Expand"), pretty, args)
    143 endfunction
    144 
    145 function! s:Expand(dict, pretty, args)
    146     try
    147         let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
    148 
    149         if a:pretty =~? '^\%(everybody_loops$\|flowgraph=\)'
    150             let flag = '--xpretty'
    151         else
    152             let flag = '--pretty'
    153         endif
    154         let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
    155         let args = [relpath, '-Z', 'unstable-options', l:flag, a:pretty] + a:args
    156         let pwd = a:dict.istemp ? a:dict.tmpdir : ''
    157         let output = s:system(pwd, shellescape(rustc) . " " . join(map(args, 'shellescape(v:val)')))
    158         if v:shell_error
    159             echohl WarningMsg
    160             echo output
    161             echohl None
    162         else
    163             new
    164             silent put =output
    165             1
    166             d
    167             setl filetype=rust
    168             setl buftype=nofile
    169             setl bufhidden=hide
    170             setl noswapfile
    171             " give the buffer a nice name
    172             let suffix = 1
    173             let basename = fnamemodify(a:dict.path, ':t:r')
    174             while 1
    175                 let bufname = basename
    176                 if suffix > 1 | let bufname .= ' ('.suffix.')' | endif
    177                 let bufname .= '.pretty.rs'
    178                 if bufexists(bufname)
    179                     let suffix += 1
    180                     continue
    181                 endif
    182                 exe 'silent noautocmd keepalt file' fnameescape(bufname)
    183                 break
    184             endwhile
    185         endif
    186     endtry
    187 endfunction
    188 
    189 function! rust#CompleteExpand(lead, line, pos)
    190     if a:line[: a:pos-1] =~# '^RustExpand!\s*\S*$'
    191         " first argument and it has a !
    192         let list = ["normal", "expanded", "typed", "expanded,identified", "flowgraph=", "everybody_loops"]
    193         if !empty(a:lead)
    194             call filter(list, "v:val[:len(a:lead)-1] == a:lead")
    195         endif
    196         return list
    197     endif
    198 
    199     return glob(escape(a:lead, "*?[") . '*', 0, 1)
    200 endfunction
    201 
    202 " Emit {{{1
    203 
    204 function! rust#Emit(type, args)
    205     let args = s:ShellTokenize(a:args)
    206     call s:WithPath(function("s:Emit"), a:type, args)
    207 endfunction
    208 
    209 function! s:Emit(dict, type, args)
    210     try
    211         let output_path = a:dict.tmpdir.'/output'
    212 
    213         let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
    214 
    215         let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
    216         let args = [relpath, '--emit', a:type, '-o', output_path] + a:args
    217         let pwd = a:dict.istemp ? a:dict.tmpdir : ''
    218         let output = s:system(pwd, shellescape(rustc) . " " . join(map(args, 'shellescape(v:val)')))
    219         if output !=# ''
    220             echohl WarningMsg
    221             echo output
    222             echohl None
    223         endif
    224         if !v:shell_error
    225             new
    226             exe 'silent keepalt read' fnameescape(output_path)
    227             1
    228             d
    229             if a:type ==# "llvm-ir"
    230                 setl filetype=llvm
    231                 let extension = 'll'
    232             elseif a:type ==# "asm"
    233                 setl filetype=asm
    234                 let extension = 's'
    235             endif
    236             setl buftype=nofile
    237             setl bufhidden=hide
    238             setl noswapfile
    239             if exists('l:extension')
    240                 " give the buffer a nice name
    241                 let suffix = 1
    242                 let basename = fnamemodify(a:dict.path, ':t:r')
    243                 while 1
    244                     let bufname = basename
    245                     if suffix > 1 | let bufname .= ' ('.suffix.')' | endif
    246                     let bufname .= '.'.extension
    247                     if bufexists(bufname)
    248                         let suffix += 1
    249                         continue
    250                     endif
    251                     exe 'silent noautocmd keepalt file' fnameescape(bufname)
    252                     break
    253                 endwhile
    254             endif
    255         endif
    256     endtry
    257 endfunction
    258 
    259 " Utility functions {{{1
    260 
    261 " Invokes func(dict, ...)
    262 " Where {dict} is a dictionary with the following keys:
    263 "   'path' - The path to the file
    264 "   'tmpdir' - The path to a temporary directory that will be deleted when the
    265 "              function returns.
    266 "   'istemp' - 1 if the path is a file inside of {dict.tmpdir} or 0 otherwise.
    267 " If {istemp} is 1 then an additional key is provided:
    268 "   'tmpdir_relpath' - The {path} relative to the {tmpdir}.
    269 "
    270 " {dict.path} may be a path to a file inside of {dict.tmpdir} or it may be the
    271 " existing path of the current buffer. If the path is inside of {dict.tmpdir}
    272 " then it is guaranteed to have a '.rs' extension.
    273 function! s:WithPath(func, ...)
    274     let buf = bufnr('')
    275     let saved = {}
    276     let dict = {}
    277     try
    278         let saved.write = &write
    279         set write
    280         let dict.path = expand('%')
    281         let pathisempty = empty(dict.path)
    282 
    283         " Always create a tmpdir in case the wrapped command wants it
    284         let dict.tmpdir = tempname()
    285         call mkdir(dict.tmpdir)
    286 
    287         if pathisempty || !saved.write
    288             let dict.istemp = 1
    289             " if we're doing this because of nowrite, preserve the filename
    290             if !pathisempty
    291                 let filename = expand('%:t:r').".rs"
    292             else
    293                 let filename = 'unnamed.rs'
    294             endif
    295             let dict.tmpdir_relpath = filename
    296             let dict.path = dict.tmpdir.'/'.filename
    297 
    298             let saved.mod = &modified
    299             set nomodified
    300 
    301             silent exe 'keepalt write! ' . fnameescape(dict.path)
    302             if pathisempty
    303                 silent keepalt 0file
    304             endif
    305         else
    306             let dict.istemp = 0
    307             update
    308         endif
    309 
    310         call call(a:func, [dict] + a:000)
    311     finally
    312         if bufexists(buf)
    313             for [opt, value] in items(saved)
    314                 silent call setbufvar(buf, '&'.opt, value)
    315                 unlet value " avoid variable type mismatches
    316             endfor
    317         endif
    318         if has_key(dict, 'tmpdir') | silent call s:RmDir(dict.tmpdir) | endif
    319     endtry
    320 endfunction
    321 
    322 function! rust#AppendCmdLine(text)
    323     call setcmdpos(getcmdpos())
    324     let cmd = getcmdline() . a:text
    325     return cmd
    326 endfunction
    327 
    328 " Tokenize the string according to sh parsing rules
    329 function! s:ShellTokenize(text)
    330     " states:
    331     " 0: start of word
    332     " 1: unquoted
    333     " 2: unquoted backslash
    334     " 3: double-quote
    335     " 4: double-quoted backslash
    336     " 5: single-quote
    337     let l:state = 0
    338     let l:current = ''
    339     let l:args = []
    340     for c in split(a:text, '\zs')
    341         if l:state == 0 || l:state == 1 " unquoted
    342             if l:c ==# ' '
    343                 if l:state == 0 | continue | endif
    344                 call add(l:args, l:current)
    345                 let l:current = ''
    346                 let l:state = 0
    347             elseif l:c ==# '\'
    348                 let l:state = 2
    349             elseif l:c ==# '"'
    350                 let l:state = 3
    351             elseif l:c ==# "'"
    352                 let l:state = 5
    353             else
    354                 let l:current .= l:c
    355                 let l:state = 1
    356             endif
    357         elseif l:state == 2 " unquoted backslash
    358             if l:c !=# "\n" " can it even be \n?
    359                 let l:current .= l:c
    360             endif
    361             let l:state = 1
    362         elseif l:state == 3 " double-quote
    363             if l:c ==# '\'
    364                 let l:state = 4
    365             elseif l:c ==# '"'
    366                 let l:state = 1
    367             else
    368                 let l:current .= l:c
    369             endif
    370         elseif l:state == 4 " double-quoted backslash
    371             if stridx('$`"\', l:c) >= 0
    372                 let l:current .= l:c
    373             elseif l:c ==# "\n" " is this even possible?
    374                 " skip it
    375             else
    376                 let l:current .= '\'.l:c
    377             endif
    378             let l:state = 3
    379         elseif l:state == 5 " single-quoted
    380             if l:c ==# "'"
    381                 let l:state = 1
    382             else
    383                 let l:current .= l:c
    384             endif
    385         endif
    386     endfor
    387     if l:state != 0
    388         call add(l:args, l:current)
    389     endif
    390     return l:args
    391 endfunction
    392 
    393 function! s:RmDir(path)
    394     " sanity check; make sure it's not empty, /, or $HOME
    395     if empty(a:path)
    396         echoerr 'Attempted to delete empty path'
    397         return 0
    398     elseif a:path ==# '/' || a:path ==# $HOME
    399         let l:path = expand(a:path)
    400         if l:path ==# '/' || l:path ==# $HOME
    401             echoerr 'Attempted to delete protected path: ' . a:path
    402             return 0
    403         endif
    404     endif
    405 
    406     if !isdirectory(a:path)
    407         return 0
    408     endif
    409 
    410     " delete() returns 0 when removing file successfully
    411     return delete(a:path, 'rf') == 0
    412 endfunction
    413 
    414 " Executes {cmd} with the cwd set to {pwd}, without changing Vim's cwd.
    415 " If {pwd} is the empty string then it doesn't change the cwd.
    416 function! s:system(pwd, cmd)
    417     let cmd = a:cmd
    418     if !empty(a:pwd)
    419         let cmd = 'cd ' . shellescape(a:pwd) . ' && ' . cmd
    420     endif
    421     return system(cmd)
    422 endfunction
    423 
    424 " Playpen Support {{{1
    425 " Parts of gist.vim by Yasuhiro Matsumoto <mattn.jp@gmail.com> reused
    426 " gist.vim available under the BSD license, available at
    427 " http://github.com/mattn/gist-vim
    428 function! s:has_webapi()
    429     if !exists("*webapi#http#post")
    430         try
    431             call webapi#http#post()
    432         catch
    433         endtry
    434     endif
    435     return exists("*webapi#http#post")
    436 endfunction
    437 
    438 function! rust#Play(count, line1, line2, ...) abort
    439     redraw
    440 
    441     let l:rust_playpen_url = get(g:, 'rust_playpen_url', 'https://play.rust-lang.org/')
    442     let l:rust_shortener_url = get(g:, 'rust_shortener_url', 'https://is.gd/')
    443 
    444     if !s:has_webapi()
    445         echohl ErrorMsg | echomsg ':RustPlay depends on webapi.vim (https://github.com/mattn/webapi-vim)' | echohl None
    446         return
    447     endif
    448 
    449     let bufname = bufname('%')
    450     if a:count < 1
    451         let content = join(getline(a:line1, a:line2), "\n")
    452     else
    453         let save_regcont = @"
    454         let save_regtype = getregtype('"')
    455         silent! normal! gvy
    456         let content = @"
    457         call setreg('"', save_regcont, save_regtype)
    458     endif
    459 
    460     let url = l:rust_playpen_url."?code=".webapi#http#encodeURI(content)
    461 
    462     if strlen(url) > 5000
    463         echohl ErrorMsg | echomsg 'Buffer too large, max 5000 encoded characters ('.strlen(url).')' | echohl None
    464         return
    465     endif
    466 
    467     let payload = "format=simple&url=".webapi#http#encodeURI(url)
    468     let res = webapi#http#post(l:rust_shortener_url.'create.php', payload, {})
    469     if res.status[0] ==# '2'
    470         let url = res.content
    471     endif
    472 
    473     let footer = ''
    474     if exists('g:rust_clip_command')
    475         call system(g:rust_clip_command, url)
    476         if !v:shell_error
    477             let footer = ' (copied to clipboard)'
    478         endif
    479     endif
    480     redraw | echomsg 'Done: '.url.footer
    481 endfunction
    482 
    483 " Run a test under the cursor or all tests {{{1
    484 
    485 " Finds a test function name under the cursor. Returns empty string when a
    486 " test function is not found.
    487 function! s:SearchTestFunctionNameUnderCursor() abort
    488     let cursor_line = line('.')
    489 
    490     " Find #[test] attribute
    491     if search('\m\C#\[test\]', 'bcW') is 0
    492         return ''
    493     endif
    494 
    495     " Move to an opening brace of the test function
    496     let test_func_line = search('\m\C^\s*fn\s\+\h\w*\s*(.\+{$', 'eW')
    497     if test_func_line is 0
    498         return ''
    499     endif
    500 
    501     " Search the end of test function (closing brace) to ensure that the
    502     " cursor position is within function definition
    503     if maparg('<Plug>(MatchitNormalForward)') ==# ''
    504         keepjumps normal! %
    505     else
    506         " Prefer matchit.vim official plugin to native % since the plugin
    507         " provides better behavior than original % (#391)
    508         " To load the plugin, run:
    509         "   :packadd matchit
    510         execute 'keepjumps' 'normal' "\<Plug>(MatchitNormalForward)"
    511     endif
    512     if line('.') < cursor_line
    513         return ''
    514     endif
    515 
    516     return matchstr(getline(test_func_line), '\m\C^\s*fn\s\+\zs\h\w*')
    517 endfunction
    518 
    519 function! rust#Test(mods, winsize, all, options) abort
    520     let manifest = findfile('Cargo.toml', expand('%:p:h') . ';')
    521     if manifest ==# ''
    522         return rust#Run(1, '--test ' . a:options)
    523     endif
    524 
    525     " <count> defaults to 0, but we prefer an empty string
    526     let winsize = a:winsize ? a:winsize : ''
    527 
    528     if has('terminal')
    529         if has('patch-8.0.910')
    530             let cmd = printf('%s noautocmd %snew | terminal ++curwin ', a:mods, winsize)
    531         else
    532             let cmd = printf('%s terminal ', a:mods)
    533         endif
    534     elseif has('nvim')
    535         let cmd = printf('%s noautocmd %snew | terminal ', a:mods, winsize)
    536     else
    537         let cmd = '!'
    538         let manifest = shellescape(manifest)
    539     endif
    540 
    541     if a:all
    542         if a:options ==# ''
    543             execute cmd . 'cargo test --manifest-path' manifest
    544         else
    545             execute cmd . 'cargo test --manifest-path' manifest a:options
    546         endif
    547         return
    548     endif
    549 
    550     let saved = getpos('.')
    551     try
    552         let func_name = s:SearchTestFunctionNameUnderCursor()
    553     finally
    554         call setpos('.', saved)
    555     endtry
    556     if func_name ==# ''
    557         echohl ErrorMsg
    558         echomsg 'No test function was found under the cursor. Please add ! to command if you want to run all tests'
    559         echohl None
    560         return
    561     endif
    562     if a:options ==# ''
    563         execute cmd . 'cargo test --manifest-path' manifest func_name
    564     else
    565         execute cmd . 'cargo test --manifest-path' manifest func_name a:options
    566     endif
    567 endfunction
    568 
    569 " }}}1
    570 
    571 " vim: set et sw=4 sts=4 ts=8: