rust.vim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. " Author: Kevin Ballard
  2. " Description: Helper functions for Rust commands/mappings
  3. " Last Modified: May 27, 2014
  4. " For bugs, patches and license go to https://github.com/rust-lang/rust.vim
  5. " Jump {{{1
  6. function! rust#Jump(mode, function) range
  7. let cnt = v:count1
  8. normal! m'
  9. if a:mode ==# 'v'
  10. norm! gv
  11. endif
  12. let foldenable = &foldenable
  13. set nofoldenable
  14. while cnt > 0
  15. execute "call <SID>Jump_" . a:function . "()"
  16. let cnt = cnt - 1
  17. endwhile
  18. let &foldenable = foldenable
  19. endfunction
  20. function! s:Jump_Back()
  21. call search('{', 'b')
  22. keepjumps normal! w99[{
  23. endfunction
  24. function! s:Jump_Forward()
  25. normal! j0
  26. call search('{', 'b')
  27. keepjumps normal! w99[{%
  28. call search('{')
  29. endfunction
  30. " Run {{{1
  31. function! rust#Run(bang, args)
  32. let args = s:ShellTokenize(a:args)
  33. if a:bang
  34. let idx = index(l:args, '--')
  35. if idx != -1
  36. let rustc_args = idx == 0 ? [] : l:args[:idx-1]
  37. let args = l:args[idx+1:]
  38. else
  39. let rustc_args = l:args
  40. let args = []
  41. endif
  42. else
  43. let rustc_args = []
  44. endif
  45. let b:rust_last_rustc_args = l:rustc_args
  46. let b:rust_last_args = l:args
  47. call s:WithPath(function("s:Run"), rustc_args, args)
  48. endfunction
  49. function! s:Run(dict, rustc_args, args)
  50. let exepath = a:dict.tmpdir.'/'.fnamemodify(a:dict.path, ':t:r')
  51. if has('win32')
  52. let exepath .= '.exe'
  53. endif
  54. let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
  55. let rustc_args = [relpath, '-o', exepath] + a:rustc_args
  56. let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
  57. let pwd = a:dict.istemp ? a:dict.tmpdir : ''
  58. let output = s:system(pwd, shellescape(rustc) . " " . join(map(rustc_args, 'shellescape(v:val)')))
  59. if output != ''
  60. echohl WarningMsg
  61. echo output
  62. echohl None
  63. endif
  64. if !v:shell_error
  65. exe '!' . shellescape(exepath) . " " . join(map(a:args, 'shellescape(v:val)'))
  66. endif
  67. endfunction
  68. " Expand {{{1
  69. function! rust#Expand(bang, args)
  70. let args = s:ShellTokenize(a:args)
  71. if a:bang && !empty(l:args)
  72. let pretty = remove(l:args, 0)
  73. else
  74. let pretty = "expanded"
  75. endif
  76. call s:WithPath(function("s:Expand"), pretty, args)
  77. endfunction
  78. function! s:Expand(dict, pretty, args)
  79. try
  80. let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
  81. if a:pretty =~? '^\%(everybody_loops$\|flowgraph=\)'
  82. let flag = '--xpretty'
  83. else
  84. let flag = '--pretty'
  85. endif
  86. let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
  87. let args = [relpath, '-Z', 'unstable-options', l:flag, a:pretty] + a:args
  88. let pwd = a:dict.istemp ? a:dict.tmpdir : ''
  89. let output = s:system(pwd, shellescape(rustc) . " " . join(map(args, 'shellescape(v:val)')))
  90. if v:shell_error
  91. echohl WarningMsg
  92. echo output
  93. echohl None
  94. else
  95. new
  96. silent put =output
  97. 1
  98. d
  99. setl filetype=rust
  100. setl buftype=nofile
  101. setl bufhidden=hide
  102. setl noswapfile
  103. " give the buffer a nice name
  104. let suffix = 1
  105. let basename = fnamemodify(a:dict.path, ':t:r')
  106. while 1
  107. let bufname = basename
  108. if suffix > 1 | let bufname .= ' ('.suffix.')' | endif
  109. let bufname .= '.pretty.rs'
  110. if bufexists(bufname)
  111. let suffix += 1
  112. continue
  113. endif
  114. exe 'silent noautocmd keepalt file' fnameescape(bufname)
  115. break
  116. endwhile
  117. endif
  118. endtry
  119. endfunction
  120. function! rust#CompleteExpand(lead, line, pos)
  121. if a:line[: a:pos-1] =~ '^RustExpand!\s*\S*$'
  122. " first argument and it has a !
  123. let list = ["normal", "expanded", "typed", "expanded,identified", "flowgraph=", "everybody_loops"]
  124. if !empty(a:lead)
  125. call filter(list, "v:val[:len(a:lead)-1] == a:lead")
  126. endif
  127. return list
  128. endif
  129. return glob(escape(a:lead, "*?[") . '*', 0, 1)
  130. endfunction
  131. " Emit {{{1
  132. function! rust#Emit(type, args)
  133. let args = s:ShellTokenize(a:args)
  134. call s:WithPath(function("s:Emit"), a:type, args)
  135. endfunction
  136. function! s:Emit(dict, type, args)
  137. try
  138. let output_path = a:dict.tmpdir.'/output'
  139. let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
  140. let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
  141. let args = [relpath, '--emit', a:type, '-o', output_path] + a:args
  142. let pwd = a:dict.istemp ? a:dict.tmpdir : ''
  143. let output = s:system(pwd, shellescape(rustc) . " " . join(map(args, 'shellescape(v:val)')))
  144. if output != ''
  145. echohl WarningMsg
  146. echo output
  147. echohl None
  148. endif
  149. if !v:shell_error
  150. new
  151. exe 'silent keepalt read' fnameescape(output_path)
  152. 1
  153. d
  154. if a:type == "llvm-ir"
  155. setl filetype=llvm
  156. let extension = 'll'
  157. elseif a:type == "asm"
  158. setl filetype=asm
  159. let extension = 's'
  160. endif
  161. setl buftype=nofile
  162. setl bufhidden=hide
  163. setl noswapfile
  164. if exists('l:extension')
  165. " give the buffer a nice name
  166. let suffix = 1
  167. let basename = fnamemodify(a:dict.path, ':t:r')
  168. while 1
  169. let bufname = basename
  170. if suffix > 1 | let bufname .= ' ('.suffix.')' | endif
  171. let bufname .= '.'.extension
  172. if bufexists(bufname)
  173. let suffix += 1
  174. continue
  175. endif
  176. exe 'silent noautocmd keepalt file' fnameescape(bufname)
  177. break
  178. endwhile
  179. endif
  180. endif
  181. endtry
  182. endfunction
  183. " Utility functions {{{1
  184. " Invokes func(dict, ...)
  185. " Where {dict} is a dictionary with the following keys:
  186. " 'path' - The path to the file
  187. " 'tmpdir' - The path to a temporary directory that will be deleted when the
  188. " function returns.
  189. " 'istemp' - 1 if the path is a file inside of {dict.tmpdir} or 0 otherwise.
  190. " If {istemp} is 1 then an additional key is provided:
  191. " 'tmpdir_relpath' - The {path} relative to the {tmpdir}.
  192. "
  193. " {dict.path} may be a path to a file inside of {dict.tmpdir} or it may be the
  194. " existing path of the current buffer. If the path is inside of {dict.tmpdir}
  195. " then it is guaranteed to have a '.rs' extension.
  196. function! s:WithPath(func, ...)
  197. let buf = bufnr('')
  198. let saved = {}
  199. let dict = {}
  200. try
  201. let saved.write = &write
  202. set write
  203. let dict.path = expand('%')
  204. let pathisempty = empty(dict.path)
  205. " Always create a tmpdir in case the wrapped command wants it
  206. let dict.tmpdir = tempname()
  207. call mkdir(dict.tmpdir)
  208. if pathisempty || !saved.write
  209. let dict.istemp = 1
  210. " if we're doing this because of nowrite, preserve the filename
  211. if !pathisempty
  212. let filename = expand('%:t:r').".rs"
  213. else
  214. let filename = 'unnamed.rs'
  215. endif
  216. let dict.tmpdir_relpath = filename
  217. let dict.path = dict.tmpdir.'/'.filename
  218. let saved.mod = &mod
  219. set nomod
  220. silent exe 'keepalt write! ' . fnameescape(dict.path)
  221. if pathisempty
  222. silent keepalt 0file
  223. endif
  224. else
  225. let dict.istemp = 0
  226. update
  227. endif
  228. call call(a:func, [dict] + a:000)
  229. finally
  230. if bufexists(buf)
  231. for [opt, value] in items(saved)
  232. silent call setbufvar(buf, '&'.opt, value)
  233. unlet value " avoid variable type mismatches
  234. endfor
  235. endif
  236. if has_key(dict, 'tmpdir') | silent call s:RmDir(dict.tmpdir) | endif
  237. endtry
  238. endfunction
  239. function! rust#AppendCmdLine(text)
  240. call setcmdpos(getcmdpos())
  241. let cmd = getcmdline() . a:text
  242. return cmd
  243. endfunction
  244. " Tokenize the string according to sh parsing rules
  245. function! s:ShellTokenize(text)
  246. " states:
  247. " 0: start of word
  248. " 1: unquoted
  249. " 2: unquoted backslash
  250. " 3: double-quote
  251. " 4: double-quoted backslash
  252. " 5: single-quote
  253. let l:state = 0
  254. let l:current = ''
  255. let l:args = []
  256. for c in split(a:text, '\zs')
  257. if l:state == 0 || l:state == 1 " unquoted
  258. if l:c ==# ' '
  259. if l:state == 0 | continue | endif
  260. call add(l:args, l:current)
  261. let l:current = ''
  262. let l:state = 0
  263. elseif l:c ==# '\'
  264. let l:state = 2
  265. elseif l:c ==# '"'
  266. let l:state = 3
  267. elseif l:c ==# "'"
  268. let l:state = 5
  269. else
  270. let l:current .= l:c
  271. let l:state = 1
  272. endif
  273. elseif l:state == 2 " unquoted backslash
  274. if l:c !=# "\n" " can it even be \n?
  275. let l:current .= l:c
  276. endif
  277. let l:state = 1
  278. elseif l:state == 3 " double-quote
  279. if l:c ==# '\'
  280. let l:state = 4
  281. elseif l:c ==# '"'
  282. let l:state = 1
  283. else
  284. let l:current .= l:c
  285. endif
  286. elseif l:state == 4 " double-quoted backslash
  287. if stridx('$`"\', l:c) >= 0
  288. let l:current .= l:c
  289. elseif l:c ==# "\n" " is this even possible?
  290. " skip it
  291. else
  292. let l:current .= '\'.l:c
  293. endif
  294. let l:state = 3
  295. elseif l:state == 5 " single-quoted
  296. if l:c == "'"
  297. let l:state = 1
  298. else
  299. let l:current .= l:c
  300. endif
  301. endif
  302. endfor
  303. if l:state != 0
  304. call add(l:args, l:current)
  305. endif
  306. return l:args
  307. endfunction
  308. function! s:RmDir(path)
  309. " sanity check; make sure it's not empty, /, or $HOME
  310. if empty(a:path)
  311. echoerr 'Attempted to delete empty path'
  312. return 0
  313. elseif a:path == '/' || a:path == $HOME
  314. echoerr 'Attempted to delete protected path: ' . a:path
  315. return 0
  316. endif
  317. return system("rm -rf " . shellescape(a:path))
  318. endfunction
  319. " Executes {cmd} with the cwd set to {pwd}, without changing Vim's cwd.
  320. " If {pwd} is the empty string then it doesn't change the cwd.
  321. function! s:system(pwd, cmd)
  322. let cmd = a:cmd
  323. if !empty(a:pwd)
  324. let cmd = 'cd ' . shellescape(a:pwd) . ' && ' . cmd
  325. endif
  326. return system(cmd)
  327. endfunction
  328. " Playpen Support {{{1
  329. " Parts of gist.vim by Yasuhiro Matsumoto <mattn.jp@gmail.com> reused
  330. " gist.vim available under the BSD license, available at
  331. " http://github.com/mattn/gist-vim
  332. function! s:has_webapi()
  333. if !exists("*webapi#http#post")
  334. try
  335. call webapi#http#post()
  336. catch
  337. endtry
  338. endif
  339. return exists("*webapi#http#post")
  340. endfunction
  341. function! rust#Play(count, line1, line2, ...) abort
  342. redraw
  343. let l:rust_playpen_url = get(g:, 'rust_playpen_url', 'https://play.rust-lang.org/')
  344. let l:rust_shortener_url = get(g:, 'rust_shortener_url', 'https://is.gd/')
  345. if !s:has_webapi()
  346. echohl ErrorMsg | echomsg ':RustPlay depends on webapi.vim (https://github.com/mattn/webapi-vim)' | echohl None
  347. return
  348. endif
  349. let bufname = bufname('%')
  350. if a:count < 1
  351. let content = join(getline(a:line1, a:line2), "\n")
  352. else
  353. let save_regcont = @"
  354. let save_regtype = getregtype('"')
  355. silent! normal! gvy
  356. let content = @"
  357. call setreg('"', save_regcont, save_regtype)
  358. endif
  359. let body = l:rust_playpen_url."?code=".webapi#http#encodeURI(content)
  360. if strlen(body) > 5000
  361. echohl ErrorMsg | echomsg 'Buffer too large, max 5000 encoded characters ('.strlen(body).')' | echohl None
  362. return
  363. endif
  364. let payload = "format=simple&url=".webapi#http#encodeURI(body)
  365. let res = webapi#http#post(l:rust_shortener_url.'create.php', payload, {})
  366. let url = res.content
  367. redraw | echomsg 'Done: '.url
  368. endfunction
  369. " }}}1
  370. " vim: set noet sw=8 ts=8: