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