mirror of
1
0
Fork 0

Merge branch 'master' of github.com:amix/vimrc

This commit is contained in:
Amir Salihefendic 2019-11-16 18:41:26 +01:00
commit ff0ede6b30
19 changed files with 1122 additions and 199 deletions

View File

@ -90,6 +90,7 @@ I recommend reading the docs of these plugins to understand them better. Each pl
* [ack.vim](https://github.com/mileszs/ack.vim): Vim plugin for `the_silver_searcher` (ag) or ack -- a wicked fast grep * [ack.vim](https://github.com/mileszs/ack.vim): Vim plugin for `the_silver_searcher` (ag) or ack -- a wicked fast grep
* [bufexplorer.zip](https://github.com/vim-scripts/bufexplorer.zip): Quickly and easily switch between buffers. This plugin can be opened with `<leader+o>` * [bufexplorer.zip](https://github.com/vim-scripts/bufexplorer.zip): Quickly and easily switch between buffers. This plugin can be opened with `<leader+o>`
* [ctrlp.vim](https://github.com/ctrlpvim/ctrlp.vim): Fuzzy file, buffer, mru and tag finder. It's mapped to `<Ctrl+F>` * [ctrlp.vim](https://github.com/ctrlpvim/ctrlp.vim): Fuzzy file, buffer, mru and tag finder. It's mapped to `<Ctrl+F>`
* [comfortable-motion.vim](https://github.com/yuttie/comfortable-motion.vim): Brings physics-based smooth scrolling to the Vim world!
* [goyo.vim](https://github.com/junegunn/goyo.vim) and [vim-zenroom2](https://github.com/amix/vim-zenroom2): * [goyo.vim](https://github.com/junegunn/goyo.vim) and [vim-zenroom2](https://github.com/amix/vim-zenroom2):
* [lightline.vim](https://github.com/itchyny/lightline.vim): A light and configurable statusline/tabline for Vim * [lightline.vim](https://github.com/itchyny/lightline.vim): A light and configurable statusline/tabline for Vim
* [NERD Tree](https://github.com/scrooloose/nerdtree): A tree explorer plugin for vim * [NERD Tree](https://github.com/scrooloose/nerdtree): A tree explorer plugin for vim

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,25 @@
Copyright (c) 2015 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -2,17 +2,15 @@
## Description ## Description
This is a vim plugin provides [Rust][r] file detection and syntax highlighting. This is a Vim plugin that provides [Rust][r] file detection, syntax highlighting, formatting,
[Syntastic][syn] integration, and more.
It is synchronized daily to the vim support code in [rust-lang/rust][rr]'s
master branch via cronjob.
## Installation ## Installation
### Using [Vundle][v] ### Using [Vundle][v]
1. Add `Plugin 'wting/rust.vim'` to `~/.vimrc` 1. Add `Plugin 'rust-lang/rust.vim'` to `~/.vimrc`
2. `vim +PluginInstall +qall` 2. `:PluginInstall` or `$ vim +PluginInstall +qall`
*Note:* Vundle will not automatically detect Rust files properly if `filetype *Note:* Vundle will not automatically detect Rust files properly if `filetype
on` is executed before Vundle. Please check the [quickstart][vqs] for more on` is executed before Vundle. Please check the [quickstart][vqs] for more
@ -20,11 +18,80 @@ details.
### Using [Pathogen][p] ### Using [Pathogen][p]
1. `cd ~/.vim/bundle` ```shell
2. `git clone https://github.com/wting/rust.vim.git` git clone --depth=1 https://github.com/rust-lang/rust.vim.git ~/.vim/bundle/rust.vim
```
[rr]: https://github.com/rust-lang/rust ### Using [NeoBundle][nb]
[p]: https://github.com/tpope/vim-pathogen
[r]: https://en.wikipedia.org/wiki/Rust_language 1. Add `NeoBundle 'rust-lang/rust.vim'` to `~/.vimrc`
2. Re-open vim or execute `:source ~/.vimrc`
### Using [vim-plug][vp]
1. Add `Plug 'rust-lang/rust.vim'` to `~/.vimrc`
2. `:PlugInstall` or `$ vim +PlugInstall +qall`
## Features
### Error checking with [Syntastic][syn]
`rust.vim` automatically registers `rustc` as a syntax checker
with [Syntastic][syn]. Check Syntastic's documentation for
information on how to customize its behaviour.
### Formatting with [rustfmt][rfmt]
The `:RustFmt` command will format your code with
[rustfmt][rfmt] if installed.
Placing `let g:rustfmt_autosave = 1` in your `~/.vimrc` will
enable automatic running of `:RustFmt` when you save a buffer.
Do `:help :RustFmt` for further formatting help and customization
options.
### [Playpen][pp] integration
*Note:* This feature requires [webapi-vim][wav] to be installed.
The `:RustPlay` command will send the current selection, or if
nothing is selected the current buffer, to the [Rust playpen][pp].
If you set g:rust_clip_command RustPlay will copy the url to the clipboard.
- Mac:
let g:rust_clip_command = 'pbcopy'
- Linux:
let g:rust_clip_command = 'xclip -selection clipboard'
[rfmt]: https://crates.io/crates/rustfmt/
## Help
Further help can be found in the documentation with `:Helptags` then `:help rust`.
Detailed help can be found in the documentation with `:help rust`.
Helptags (`:help helptags`) need to be generated for this plugin
in order to navigate the help. Most plugin managers will do this
automatically, but check their documentation if that is not the case.
## License
Like Rust, rust.vim is primarily distributed under the terms of both the MIT
license and the Apache License (Version 2.0). See LICENSE-APACHE and
LICENSE-MIT for details.
[r]: https://www.rust-lang.org
[v]: https://github.com/gmarik/vundle [v]: https://github.com/gmarik/vundle
[vqs]: https://github.com/gmarik/vundle#quick-start [vqs]: https://github.com/gmarik/vundle#quick-start
[p]: https://github.com/tpope/vim-pathogen
[nb]: https://github.com/Shougo/neobundle.vim
[vp]: https://github.com/junegunn/vim-plug
[rfmt]: https://github.com/rust-lang-nursery/rustfmt
[syn]: https://github.com/scrooloose/syntastic
[wav]: https://github.com/mattn/webapi-vim
[pp]: https://play.rust-lang.org/

View File

@ -1,9 +1,9 @@
if !exists('g:rust_conceal') || !has('conceal') || &enc != 'utf-8' if !exists('g:rust_conceal') || g:rust_conceal == 0 || !has('conceal') || &enc != 'utf-8'
finish finish
endif endif
" For those who don't want to see `::`... " For those who don't want to see `::`...
if exists('g:rust_conceal_mod_path') if exists('g:rust_conceal_mod_path') && g:rust_conceal_mod_path != 0
syn match rustNiceOperator "::" conceal cchar= syn match rustNiceOperator "::" conceal cchar=
endif endif
@ -18,7 +18,7 @@ syn match rustNiceOperator "=>" contains=rustFatRightArrowHead,rustFatRightArrow
syn match rustNiceOperator /\<\@!_\(_*\>\)\@=/ conceal cchar= syn match rustNiceOperator /\<\@!_\(_*\>\)\@=/ conceal cchar=
" For those who don't want to see `pub`... " For those who don't want to see `pub`...
if exists('g:rust_conceal_pub') if exists('g:rust_conceal_pub') && g:rust_conceal_pub != 0
syn match rustPublicSigil contained "pu" conceal cchar= syn match rustPublicSigil contained "pu" conceal cchar=
syn match rustPublicRest contained "b" conceal cchar=  syn match rustPublicRest contained "b" conceal cchar= 
syn match rustNiceOperator "pub " contains=rustPublicSigil,rustPublicRest syn match rustNiceOperator "pub " contains=rustPublicSigil,rustPublicRest
@ -26,6 +26,9 @@ endif
hi link rustNiceOperator Operator hi link rustNiceOperator Operator
if !exists('g:rust_conceal_mod_path') if !(exists('g:rust_conceal_mod_path') && g:rust_conceal_mod_path != 0)
hi! link Conceal Operator hi! link Conceal Operator
" And keep it after a colorscheme change
au ColorScheme <buffer> hi! link Conceal Operator
endif endif

View File

@ -0,0 +1,85 @@
function! cargo#cmd(args)
silent! clear
if !a:args
execute "!" . "cargo ". a:args
else
echom "Missing arguments"
endif
endfunction
function! cargo#build(args)
silent! clear
if !a:args
execute "!" . "cargo build " . a:args
else
execute "!" . "cargo build"
endif
silent! clear
execute "!" . "cargo build"
endfunction
function! cargo#clean(args)
silent! clear
if !a:args
execute "!" . "cargo clean " . a:args
else
execute "!" . "cargo clean"
endif
silent! clear
execute "!" . "cargo clean"
endfunction
function! cargo#doc(args)
silent! clear
if !a:args
execute "!" . "cargo doc " . a:args
else
execute "!" . "cargo doc"
endif
endfunction
function! cargo#new(args)
silent! clear
if !a:args
execute "!cargo new " . a:args
:cd `=a:args`
else
echom "Missing arguments"
endif
endfunction
function! cargo#init(args)
silent! clear
if !a:args
execute "!" . "cargo init " . a:args
else
execute "!" . "cargo init"
endif
endfunction
function! cargo#run(args)
silent! clear
if !a:args
execute "!" . "cargo run " . a:args
else
execute "!" . "cargo run"
endif
endfunction
function! cargo#test(args)
silent! clear
if !a:args
execute "!" . "cargo test " . a:args
else
execute "!" . "cargo test"
endif
endfunction
function! cargo#bench(args)
silent! clear
if !a:args
execute "!" . "cargo bench " . a:args
else
execute "!" . "cargo bench"
endif
endfunction

View File

@ -1,6 +1,7 @@
" Author: Kevin Ballard " Author: Kevin Ballard
" Description: Helper functions for Rust commands/mappings " Description: Helper functions for Rust commands/mappings
" Last Modified: May 27, 2014 " Last Modified: May 27, 2014
" For bugs, patches and license go to https://github.com/rust-lang/rust.vim
" Jump {{{1 " Jump {{{1
@ -34,72 +35,74 @@ endfunction
" Run {{{1 " Run {{{1
function! rust#Run(bang, args) function! rust#Run(bang, args)
let args = s:ShellTokenize(a:args)
if a:bang if a:bang
let idx = index(a:args, '--') let idx = index(l:args, '--')
if idx != -1 if idx != -1
let rustc_args = idx == 0 ? [] : a:args[:idx-1] let rustc_args = idx == 0 ? [] : l:args[:idx-1]
let args = a:args[idx+1:] let args = l:args[idx+1:]
else else
let rustc_args = a:args let rustc_args = l:args
let args = [] let args = []
endif endif
else else
let rustc_args = [] let rustc_args = []
let args = a:args
endif endif
let b:rust_last_rustc_args = rustc_args let b:rust_last_rustc_args = l:rustc_args
let b:rust_last_args = args let b:rust_last_args = l:args
call s:WithPath(function("s:Run"), rustc_args, args) call s:WithPath(function("s:Run"), rustc_args, args)
endfunction endfunction
function! s:Run(path, rustc_args, args) function! s:Run(dict, rustc_args, args)
try let exepath = a:dict.tmpdir.'/'.fnamemodify(a:dict.path, ':t:r')
let exepath = tempname() if has('win32')
if has('win32') let exepath .= '.exe'
let exepath .= '.exe' endif
endif
let rustc_args = [a:path, '-o', exepath] + a:rustc_args let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
let rustc_args = [relpath, '-o', exepath] + a:rustc_args
let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc" let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
let output = system(shellescape(rustc) . " " . join(map(rustc_args, 'shellescape(v:val)'))) let pwd = a:dict.istemp ? a:dict.tmpdir : ''
if output != '' let output = s:system(pwd, shellescape(rustc) . " " . join(map(rustc_args, 'shellescape(v:val)')))
echohl WarningMsg if output != ''
echo output echohl WarningMsg
echohl None echo output
endif echohl None
if !v:shell_error endif
exe '!' . shellescape(exepath) . " " . join(map(a:args, 'shellescape(v:val)')) if !v:shell_error
endif exe '!' . shellescape(exepath) . " " . join(map(a:args, 'shellescape(v:val)'))
finally endif
if exists("exepath")
silent! call delete(exepath)
endif
endtry
endfunction endfunction
" Expand {{{1 " Expand {{{1
function! rust#Expand(bang, args) function! rust#Expand(bang, args)
if a:bang && !empty(a:args) let args = s:ShellTokenize(a:args)
let pretty = a:args[0] if a:bang && !empty(l:args)
let args = a:args[1:] let pretty = remove(l:args, 0)
else else
let pretty = "expanded" let pretty = "expanded"
let args = a:args
endif endif
call s:WithPath(function("s:Expand"), pretty, args) call s:WithPath(function("s:Expand"), pretty, args)
endfunction endfunction
function! s:Expand(path, pretty, args) function! s:Expand(dict, pretty, args)
try try
let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc" let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
let args = [a:path, '--pretty', a:pretty] + a:args if a:pretty =~? '^\%(everybody_loops$\|flowgraph=\)'
let output = system(shellescape(rustc) . " " . join(map(args, "shellescape(v:val)"))) let flag = '--xpretty'
else
let flag = '--pretty'
endif
let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
let args = [relpath, '-Z', 'unstable-options', l:flag, a:pretty] + a:args
let pwd = a:dict.istemp ? a:dict.tmpdir : ''
let output = s:system(pwd, shellescape(rustc) . " " . join(map(args, 'shellescape(v:val)')))
if v:shell_error if v:shell_error
echohl WarningMsg echohl WarningMsg
echo output echo output
@ -113,6 +116,20 @@ function! s:Expand(path, pretty, args)
setl buftype=nofile setl buftype=nofile
setl bufhidden=hide setl bufhidden=hide
setl noswapfile setl noswapfile
" give the buffer a nice name
let suffix = 1
let basename = fnamemodify(a:dict.path, ':t:r')
while 1
let bufname = basename
if suffix > 1 | let bufname .= ' ('.suffix.')' | endif
let bufname .= '.pretty.rs'
if bufexists(bufname)
let suffix += 1
continue
endif
exe 'silent noautocmd keepalt file' fnameescape(bufname)
break
endwhile
endif endif
endtry endtry
endfunction endfunction
@ -120,7 +137,7 @@ endfunction
function! rust#CompleteExpand(lead, line, pos) function! rust#CompleteExpand(lead, line, pos)
if a:line[: a:pos-1] =~ '^RustExpand!\s*\S*$' if a:line[: a:pos-1] =~ '^RustExpand!\s*\S*$'
" first argument and it has a ! " first argument and it has a !
let list = ["normal", "expanded", "typed", "expanded,identified", "flowgraph="] let list = ["normal", "expanded", "typed", "expanded,identified", "flowgraph=", "everybody_loops"]
if !empty(a:lead) if !empty(a:lead)
call filter(list, "v:val[:len(a:lead)-1] == a:lead") call filter(list, "v:val[:len(a:lead)-1] == a:lead")
endif endif
@ -133,72 +150,120 @@ endfunction
" Emit {{{1 " Emit {{{1
function! rust#Emit(type, args) function! rust#Emit(type, args)
call s:WithPath(function("s:Emit"), a:type, a:args) let args = s:ShellTokenize(a:args)
call s:WithPath(function("s:Emit"), a:type, args)
endfunction endfunction
function! s:Emit(path, type, args) function! s:Emit(dict, type, args)
try try
let output_path = a:dict.tmpdir.'/output'
let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc" let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
let args = [a:path, '--emit', a:type, '-o', '-'] + a:args let relpath = get(a:dict, 'tmpdir_relpath', a:dict.path)
let output = system(shellescape(rustc) . " " . join(map(args, "shellescape(v:val)"))) let args = [relpath, '--emit', a:type, '-o', output_path] + a:args
if v:shell_error let pwd = a:dict.istemp ? a:dict.tmpdir : ''
let output = s:system(pwd, shellescape(rustc) . " " . join(map(args, 'shellescape(v:val)')))
if output != ''
echohl WarningMsg echohl WarningMsg
echo output echo output
echohl None echohl None
else endif
if !v:shell_error
new new
silent put =output exe 'silent keepalt read' fnameescape(output_path)
1 1
d d
if a:type == "ir" if a:type == "llvm-ir"
setl filetype=llvm setl filetype=llvm
let extension = 'll'
elseif a:type == "asm" elseif a:type == "asm"
setl filetype=asm setl filetype=asm
let extension = 's'
endif endif
setl buftype=nofile setl buftype=nofile
setl bufhidden=hide setl bufhidden=hide
setl noswapfile setl noswapfile
if exists('l:extension')
" give the buffer a nice name
let suffix = 1
let basename = fnamemodify(a:dict.path, ':t:r')
while 1
let bufname = basename
if suffix > 1 | let bufname .= ' ('.suffix.')' | endif
let bufname .= '.'.extension
if bufexists(bufname)
let suffix += 1
continue
endif
exe 'silent noautocmd keepalt file' fnameescape(bufname)
break
endwhile
endif
endif endif
endtry endtry
endfunction endfunction
" Utility functions {{{1 " Utility functions {{{1
" Invokes func(dict, ...)
" Where {dict} is a dictionary with the following keys:
" 'path' - The path to the file
" 'tmpdir' - The path to a temporary directory that will be deleted when the
" function returns.
" 'istemp' - 1 if the path is a file inside of {dict.tmpdir} or 0 otherwise.
" If {istemp} is 1 then an additional key is provided:
" 'tmpdir_relpath' - The {path} relative to the {tmpdir}.
"
" {dict.path} may be a path to a file inside of {dict.tmpdir} or it may be the
" existing path of the current buffer. If the path is inside of {dict.tmpdir}
" then it is guaranteed to have a '.rs' extension.
function! s:WithPath(func, ...) function! s:WithPath(func, ...)
let buf = bufnr('')
let saved = {}
let dict = {}
try try
let save_write = &write let saved.write = &write
set write set write
let path = expand('%') let dict.path = expand('%')
let pathisempty = empty(path) let pathisempty = empty(dict.path)
if pathisempty || !save_write
" use a temporary file named 'unnamed.rs' inside a temporary
" directory. This produces better error messages
let tmpdir = tempname()
call mkdir(tmpdir)
let save_cwd = getcwd() " Always create a tmpdir in case the wrapped command wants it
silent exe 'lcd' fnameescape(tmpdir) let dict.tmpdir = tempname()
call mkdir(dict.tmpdir)
let path = 'unnamed.rs' if pathisempty || !saved.write
let dict.istemp = 1
" if we're doing this because of nowrite, preserve the filename
if !pathisempty
let filename = expand('%:t:r').".rs"
else
let filename = 'unnamed.rs'
endif
let dict.tmpdir_relpath = filename
let dict.path = dict.tmpdir.'/'.filename
let save_mod = &mod let saved.mod = &mod
set nomod set nomod
silent exe 'keepalt write! ' . fnameescape(path) silent exe 'keepalt write! ' . fnameescape(dict.path)
if pathisempty if pathisempty
silent keepalt 0file silent keepalt 0file
endif endif
else else
let dict.istemp = 0
update update
endif endif
call call(a:func, [path] + a:000) call call(a:func, [dict] + a:000)
finally finally
if exists("save_mod") | let &mod = save_mod | endif if bufexists(buf)
if exists("save_write") | let &write = save_write | endif for [opt, value] in items(saved)
if exists("save_cwd") | silent exe 'lcd' fnameescape(save_cwd) | endif silent call setbufvar(buf, '&'.opt, value)
if exists("tmpdir") | silent call s:RmDir(tmpdir) | endif unlet value " avoid variable type mismatches
endfor
endif
if has_key(dict, 'tmpdir') | silent call s:RmDir(dict.tmpdir) | endif
endtry endtry
endfunction endfunction
@ -208,6 +273,71 @@ function! rust#AppendCmdLine(text)
return cmd return cmd
endfunction endfunction
" Tokenize the string according to sh parsing rules
function! s:ShellTokenize(text)
" states:
" 0: start of word
" 1: unquoted
" 2: unquoted backslash
" 3: double-quote
" 4: double-quoted backslash
" 5: single-quote
let l:state = 0
let l:current = ''
let l:args = []
for c in split(a:text, '\zs')
if l:state == 0 || l:state == 1 " unquoted
if l:c ==# ' '
if l:state == 0 | continue | endif
call add(l:args, l:current)
let l:current = ''
let l:state = 0
elseif l:c ==# '\'
let l:state = 2
elseif l:c ==# '"'
let l:state = 3
elseif l:c ==# "'"
let l:state = 5
else
let l:current .= l:c
let l:state = 1
endif
elseif l:state == 2 " unquoted backslash
if l:c !=# "\n" " can it even be \n?
let l:current .= l:c
endif
let l:state = 1
elseif l:state == 3 " double-quote
if l:c ==# '\'
let l:state = 4
elseif l:c ==# '"'
let l:state = 1
else
let l:current .= l:c
endif
elseif l:state == 4 " double-quoted backslash
if stridx('$`"\', l:c) >= 0
let l:current .= l:c
elseif l:c ==# "\n" " is this even possible?
" skip it
else
let l:current .= '\'.l:c
endif
let l:state = 3
elseif l:state == 5 " single-quoted
if l:c == "'"
let l:state = 1
else
let l:current .= l:c
endif
endif
endfor
if l:state != 0
call add(l:args, l:current)
endif
return l:args
endfunction
function! s:RmDir(path) function! s:RmDir(path)
" sanity check; make sure it's not empty, /, or $HOME " sanity check; make sure it's not empty, /, or $HOME
if empty(a:path) if empty(a:path)
@ -217,9 +347,73 @@ function! s:RmDir(path)
echoerr 'Attempted to delete protected path: ' . a:path echoerr 'Attempted to delete protected path: ' . a:path
return 0 return 0
endif endif
silent exe "!rm -rf " . shellescape(a:path) return system("rm -rf " . shellescape(a:path))
endfunction
" Executes {cmd} with the cwd set to {pwd}, without changing Vim's cwd.
" If {pwd} is the empty string then it doesn't change the cwd.
function! s:system(pwd, cmd)
let cmd = a:cmd
if !empty(a:pwd)
let cmd = 'cd ' . shellescape(a:pwd) . ' && ' . cmd
endif
return system(cmd)
endfunction
" Playpen Support {{{1
" Parts of gist.vim by Yasuhiro Matsumoto <mattn.jp@gmail.com> reused
" gist.vim available under the BSD license, available at
" http://github.com/mattn/gist-vim
function! s:has_webapi()
if !exists("*webapi#http#post")
try
call webapi#http#post()
catch
endtry
endif
return exists("*webapi#http#post")
endfunction
function! rust#Play(count, line1, line2, ...) abort
redraw
let l:rust_playpen_url = get(g:, 'rust_playpen_url', 'https://play.rust-lang.org/')
let l:rust_shortener_url = get(g:, 'rust_shortener_url', 'https://is.gd/')
if !s:has_webapi()
echohl ErrorMsg | echomsg ':RustPlay depends on webapi.vim (https://github.com/mattn/webapi-vim)' | echohl None
return
endif
let bufname = bufname('%')
if a:count < 1
let content = join(getline(a:line1, a:line2), "\n")
else
let save_regcont = @"
let save_regtype = getregtype('"')
silent! normal! gvy
let content = @"
call setreg('"', save_regcont, save_regtype)
endif
let body = l:rust_playpen_url."?code=".webapi#http#encodeURI(content)
if strlen(body) > 5000
echohl ErrorMsg | echomsg 'Buffer too large, max 5000 encoded characters ('.strlen(body).')' | echohl None
return
endif
let payload = "format=simple&url=".webapi#http#encodeURI(body)
let res = webapi#http#post(l:rust_shortener_url.'create.php', payload, {})
let url = res.content
if exists('g:rust_clip_command')
call system(g:rust_clip_command, url)
endif
redraw | echomsg 'Done: '.url
endfunction endfunction
" }}}1 " }}}1
" vim: set noet sw=4 ts=4: " vim: set noet sw=8 ts=8:

View File

@ -0,0 +1,107 @@
" Author: Stephen Sugden <stephen@stephensugden.com>
"
" Adapted from https://github.com/fatih/vim-go
" For bugs, patches and license go to https://github.com/rust-lang/rust.vim
if !exists("g:rustfmt_autosave")
let g:rustfmt_autosave = 0
endif
if !exists("g:rustfmt_command")
let g:rustfmt_command = "rustfmt"
endif
if !exists("g:rustfmt_options")
let g:rustfmt_options = ""
endif
if !exists("g:rustfmt_fail_silently")
let g:rustfmt_fail_silently = 0
endif
let s:got_fmt_error = 0
function! s:RustfmtCommandRange(filename, line1, line2)
let l:arg = {"file": shellescape(a:filename), "range": [a:line1, a:line2]}
return printf("%s %s --write-mode=overwrite --file-lines '[%s]'", g:rustfmt_command, g:rustfmt_options, json_encode(l:arg))
endfunction
function! s:RustfmtCommand(filename)
return g:rustfmt_command . " --write-mode=overwrite " . g:rustfmt_options . " " . shellescape(a:filename)
endfunction
function! s:RunRustfmt(command, curw, tmpname)
if exists("*systemlist")
let out = systemlist(a:command)
else
let out = split(system(a:command), '\r\?\n')
endif
if v:shell_error == 0 || v:shell_error == 3
" remove undo point caused via BufWritePre
try | silent undojoin | catch | endtry
" Replace current file with temp file, then reload buffer
call rename(a:tmpname, expand('%'))
silent edit!
let &syntax = &syntax
" only clear location list if it was previously filled to prevent
" clobbering other additions
if s:got_fmt_error
let s:got_fmt_error = 0
call setloclist(0, [])
lwindow
endif
elseif g:rustfmt_fail_silently == 0
" otherwise get the errors and put them in the location list
let errors = []
for line in out
" src/lib.rs:13:5: 13:10 error: expected `,`, or `}`, found `value`
let tokens = matchlist(line, '^\(.\{-}\):\(\d\+\):\(\d\+\):\s*\(\d\+:\d\+\s*\)\?\s*error: \(.*\)')
if !empty(tokens)
call add(errors, {"filename": @%,
\"lnum": tokens[2],
\"col": tokens[3],
\"text": tokens[5]})
endif
endfor
if empty(errors)
% | " Couldn't detect rustfmt error format, output errors
endif
if !empty(errors)
call setloclist(0, errors, 'r')
echohl Error | echomsg "rustfmt returned error" | echohl None
endif
let s:got_fmt_error = 1
lwindow
" We didn't use the temp file, so clean up
call delete(a:tmpname)
endif
call winrestview(a:curw)
endfunction
function! rustfmt#FormatRange(line1, line2)
let l:curw = winsaveview()
let l:tmpname = expand("%:p:h") . "/." . expand("%:p:t") . ".rustfmt"
call writefile(getline(1, '$'), l:tmpname)
let command = s:RustfmtCommandRange(l:tmpname, a:line1, a:line2)
call s:RunRustfmt(command, l:curw, l:tmpname)
endfunction
function! rustfmt#Format()
let l:curw = winsaveview()
let l:tmpname = expand("%:p:h") . "/." . expand("%:p:t") . ".rustfmt"
call writefile(getline(1, '$'), l:tmpname)
let command = s:RustfmtCommand(l:tmpname)
call s:RunRustfmt(command, l:curw, l:tmpname)
endfunction

View File

@ -2,64 +2,36 @@
" Compiler: Cargo Compiler " Compiler: Cargo Compiler
" Maintainer: Damien Radtke <damienradtke@gmail.com> " Maintainer: Damien Radtke <damienradtke@gmail.com>
" Latest Revision: 2014 Sep 24 " Latest Revision: 2014 Sep 24
" For bugs, patches and license go to https://github.com/rust-lang/rust.vim
if exists('current_compiler') if exists('current_compiler')
finish finish
endif endif
runtime compiler/rustc.vim runtime compiler/rustc.vim
let current_compiler = "cargo" let current_compiler = "cargo"
let s:save_cpo = &cpo
set cpo&vim
if exists(':CompilerSet') != 2 if exists(':CompilerSet') != 2
command -nargs=* CompilerSet setlocal <args> command -nargs=* CompilerSet setlocal <args>
endif endif
if exists('g:cargo_makeprg_params') if exists('g:cargo_makeprg_params')
execute 'CompilerSet makeprg=cargo\ '.escape(g:cargo_makeprg_params, ' \|"').'\ $*' execute 'CompilerSet makeprg=cargo\ '.escape(g:cargo_makeprg_params, ' \|"').'\ $*'
else else
CompilerSet makeprg=cargo\ $* CompilerSet makeprg=cargo\ $*
endif endif
" Allow a configurable global Cargo.toml name. This makes it easy to " Ignore general cargo progress messages
" support variations like 'cargo.toml'. CompilerSet errorformat+=
let s:cargo_manifest_name = get(g:, 'cargo_manifest_name', 'Cargo.toml') \%-G%\\s%#Downloading%.%#,
\%-G%\\s%#Compiling%.%#,
\%-G%\\s%#Finished%.%#,
\%-G%\\s%#error:\ Could\ not\ compile\ %.%#,
\%-G%\\s%#To\ learn\ more\\,%.%#,
\%-Gnote:\ Run\ with\ \`RUST_BACKTRACE=%.%#,
\%.%#panicked\ at\ \\'%m\\'\\,\ %f:%l
function! s:is_absolute(path) let &cpo = s:save_cpo
return a:path[0] == '/' || a:path =~ '[A-Z]\+:' unlet s:save_cpo
endfunction
let s:local_manifest = findfile(s:cargo_manifest_name, '.;')
if s:local_manifest != ''
let s:local_manifest = fnamemodify(s:local_manifest, ':p:h').'/'
augroup cargo
au!
au QuickfixCmdPost make call s:FixPaths()
augroup END
" FixPaths() is run after Cargo, and is used to change the file paths
" to be relative to the current directory instead of Cargo.toml.
function! s:FixPaths()
let qflist = getqflist()
let manifest = s:local_manifest
for qf in qflist
if !qf.valid
let m = matchlist(qf.text, '(file://\(.*\))$')
if !empty(m)
let manifest = m[1].'/'
" Manually strip another slash if needed; usually just an
" issue on Windows.
if manifest =~ '^/[A-Z]\+:/'
let manifest = manifest[1:]
endif
endif
continue
endif
let filename = bufname(qf.bufnr)
if s:is_absolute(filename)
continue
endif
let qf.filename = simplify(manifest.filename)
call remove(qf, 'bufnr')
endfor
call setqflist(qflist, 'r')
endfunction
endif

View File

@ -2,9 +2,10 @@
" Compiler: Rust Compiler " Compiler: Rust Compiler
" Maintainer: Chris Morgan <me@chrismorgan.info> " Maintainer: Chris Morgan <me@chrismorgan.info>
" Latest Revision: 2013 Jul 12 " Latest Revision: 2013 Jul 12
" For bugs, patches and license go to https://github.com/rust-lang/rust.vim
if exists("current_compiler") if exists("current_compiler")
finish finish
endif endif
let current_compiler = "rustc" let current_compiler = "rustc"
@ -15,12 +16,13 @@ if exists(":CompilerSet") != 2
command -nargs=* CompilerSet setlocal <args> command -nargs=* CompilerSet setlocal <args>
endif endif
if exists("g:rustc_makeprg_no_percent") && g:rustc_makeprg_no_percent == 1 if exists("g:rustc_makeprg_no_percent") && g:rustc_makeprg_no_percent != 0
CompilerSet makeprg=rustc CompilerSet makeprg=rustc
else else
CompilerSet makeprg=rustc\ \% CompilerSet makeprg=rustc\ \%
endif endif
" Old errorformat (before nightly 2016/08/10)
CompilerSet errorformat= CompilerSet errorformat=
\%f:%l:%c:\ %t%*[^:]:\ %m, \%f:%l:%c:\ %t%*[^:]:\ %m,
\%f:%l:%c:\ %*\\d:%*\\d\ %t%*[^:]:\ %m, \%f:%l:%c:\ %*\\d:%*\\d\ %t%*[^:]:\ %m,
@ -29,5 +31,16 @@ CompilerSet errorformat=
\%-G%*[\ ]^%*[~], \%-G%*[\ ]^%*[~],
\%-G%*[\ ]... \%-G%*[\ ]...
" New errorformat (after nightly 2016/08/10)
CompilerSet errorformat+=
\%-G,
\%-Gerror:\ aborting\ %.%#,
\%-Gerror:\ Could\ not\ compile\ %.%#,
\%Eerror:\ %m,
\%Eerror[E%n]:\ %m,
\%Wwarning:\ %m,
\%Inote:\ %m,
\%C\ %#-->\ %f:%l:%c
let &cpo = s:cpo_save let &cpo = s:cpo_save
unlet s:cpo_save unlet s:cpo_save

View File

@ -1,7 +1,7 @@
*rust.txt* Filetype plugin for Rust *ft_rust.txt* Filetype plugin for Rust
============================================================================== ==============================================================================
CONTENTS *rust* *ft-rust* CONTENTS *rust*
1. Introduction |rust-intro| 1. Introduction |rust-intro|
2. Settings |rust-settings| 2. Settings |rust-settings|
@ -88,11 +88,49 @@ g:ftplugin_rust_source_path~
let g:ftplugin_rust_source_path = $HOME.'/dev/rust' let g:ftplugin_rust_source_path = $HOME.'/dev/rust'
< <
*g:cargo_manifest_name* *g:rustfmt_command*
g:cargo_manifest_name~ g:rustfmt_command~
Set this option to the name of the manifest file for your projects. If Set this option to the name of the 'rustfmt' executable in your $PATH. If
not specified it defaults to 'Cargo.toml' : > not specified it defaults to 'rustfmt' : >
let g:cargo_manifest_name = 'Cargo.toml' let g:rustfmt_command = 'rustfmt'
<
*g:rustfmt_autosave*
g:rustfmt_autosave~
Set this option to 1 to run |:RustFmt| automatically when saving a
buffer. If not specified it defaults to 0 : >
let g:rustfmt_autosave = 0
<
*g:rustfmt_fail_silently*
g:rustfmt_fail_silently~
Set this option to 1 to prevent 'rustfmt' from populating the
|location-list| with errors. If not specified it defaults to 0: >
let g:rustfmt_fail_silently = 0
<
*g:rustfmt_options*
g:rustfmt_options~
Set this option to a string of options to pass to 'rustfmt'. The
write-mode is already set to 'overwrite'. If not specified it
defaults to '' : >
let g:rustfmt_options = ''
<
*g:rust_playpen_url*
g:rust_playpen_url~
Set this option to override the url for the playpen to use: >
let g:rust_playpen_url = 'https://play.rust-lang.org/'
<
*g:rust_shortener_url*
g:rust_shortener_url~
Set this option to override the url for the url shortener: >
let g:rust_shortener_url = 'https://is.gd/'
<
*g:rust_clip_command*
g:rust_clip_command~
Set this option to the command used in your OS to copy the Rust Play
url to the clipboard: >
let g:rust_clip_command = 'xclip -selection clipboard'
< <
============================================================================== ==============================================================================
@ -157,6 +195,36 @@ COMMANDS *rust-commands*
If |g:rustc_path| is defined, it is used as the path to rustc. If |g:rustc_path| is defined, it is used as the path to rustc.
Otherwise it is assumed rustc can be found in $PATH. Otherwise it is assumed rustc can be found in $PATH.
:RustPlay *:RustPlay*
This command will only work if you have web-api.vim installed
(available at https://github.com/mattn/webapi-vim). It sends the
current selection, or if nothing is selected, the entirety of the
current buffer to the Rust playpen, and emits a message with the
shortened URL to the playpen.
|g:rust_playpen_url| is the base URL to the playpen, by default
"https://play.rust-lang.org/".
|g:rust_shortener_url| is the base url for the shorterner, by
default "https://is.gd/"
|g:rust_clip_command| is the command to run to copy the
playpen url to the clipboard of your system.
:RustFmt *:RustFmt*
Runs |g:rustfmt_command| on the current buffer. If
|g:rustfmt_options| is set then those will be passed to the
executable.
If |g:rustfmt_fail_silently| is 0 (the default) then it
will populate the |location-list| with the errors from
|g:rustfmt_command|. If |g:rustfmt_fail_silently| is set to 1
then it will not populate the |location-list|.
:RustFmtRange *:RustFmtRange*
Runs |g:rustfmt_command| with selected range. See
|:RustFmt| for any other information.
============================================================================== ==============================================================================
MAPPINGS *rust-mappings* MAPPINGS *rust-mappings*

View File

@ -1,8 +1,9 @@
" Language: Rust " Language: Rust
" Description: Vim syntax file for Rust " Description: Vim ftplugin for Rust
" Maintainer: Chris Morgan <me@chrismorgan.info> " Maintainer: Chris Morgan <me@chrismorgan.info>
" Maintainer: Kevin Ballard <kevin@sb.org> " Maintainer: Kevin Ballard <kevin@sb.org>
" Last Change: Jul 07, 2014 " Last Change: June 08, 2016
" For bugs, patches and license go to https://github.com/rust-lang/rust.vim
if exists("b:did_ftplugin") if exists("b:did_ftplugin")
finish finish
@ -12,13 +13,16 @@ let b:did_ftplugin = 1
let s:save_cpo = &cpo let s:save_cpo = &cpo
set cpo&vim set cpo&vim
augroup rust.vim
autocmd!
" Variables {{{1 " Variables {{{1
" The rust source code at present seems to typically omit a leader on /*! " The rust source code at present seems to typically omit a leader on /*!
" comments, so we'll use that as our default, but make it easy to switch. " comments, so we'll use that as our default, but make it easy to switch.
" This does not affect indentation at all (I tested it with and without " This does not affect indentation at all (I tested it with and without
" leader), merely whether a leader is inserted by default or not. " leader), merely whether a leader is inserted by default or not.
if exists("g:rust_bang_comment_leader") && g:rust_bang_comment_leader == 1 if exists("g:rust_bang_comment_leader") && g:rust_bang_comment_leader != 0
" Why is the `,s0:/*,mb:\ ,ex:*/` there, you ask? I don't understand why, " Why is the `,s0:/*,mb:\ ,ex:*/` there, you ask? I don't understand why,
" but without it, */ gets indented one space even if there were no " but without it, */ gets indented one space even if there were no
" leaders. I'm fairly sure that's a Vim bug. " leaders. I'm fairly sure that's a Vim bug.
@ -35,7 +39,7 @@ silent! setlocal formatoptions+=j
" otherwise it's better than nothing. " otherwise it's better than nothing.
setlocal smartindent nocindent setlocal smartindent nocindent
if !exists("g:rust_recommended_style") || g:rust_recommended_style == 1 if !exists("g:rust_recommended_style") || g:rust_recommended_style != 0
setlocal tabstop=4 shiftwidth=4 softtabstop=4 expandtab setlocal tabstop=4 shiftwidth=4 softtabstop=4 expandtab
setlocal textwidth=99 setlocal textwidth=99
endif endif
@ -43,7 +47,6 @@ endif
" This includeexpr isn't perfect, but it's a good start " This includeexpr isn't perfect, but it's a good start
setlocal includeexpr=substitute(v:fname,'::','/','g') setlocal includeexpr=substitute(v:fname,'::','/','g')
" NOT adding .rc as it's being phased out (0.7)
setlocal suffixesadd=.rs setlocal suffixesadd=.rs
if exists("g:ftplugin_rust_source_path") if exists("g:ftplugin_rust_source_path")
@ -54,7 +57,33 @@ if exists("g:loaded_delimitMate")
if exists("b:delimitMate_excluded_regions") if exists("b:delimitMate_excluded_regions")
let b:rust_original_delimitMate_excluded_regions = b:delimitMate_excluded_regions let b:rust_original_delimitMate_excluded_regions = b:delimitMate_excluded_regions
endif endif
let b:delimitMate_excluded_regions = delimitMate#Get("excluded_regions") . ',rustLifetimeCandidate,rustGenericLifetimeCandidate'
let s:delimitMate_extra_excluded_regions = ',rustLifetimeCandidate,rustGenericLifetimeCandidate'
" For this buffer, when delimitMate issues the `User delimitMate_map`
" event in the autocommand system, add the above-defined extra excluded
" regions to delimitMate's state, if they have not already been added.
autocmd User <buffer>
\ if expand('<afile>') ==# 'delimitMate_map' && match(
\ delimitMate#Get("excluded_regions"),
\ s:delimitMate_extra_excluded_regions) == -1
\| let b:delimitMate_excluded_regions =
\ delimitMate#Get("excluded_regions")
\ . s:delimitMate_extra_excluded_regions
\|endif
" For this buffer, when delimitMate issues the `User delimitMate_unmap`
" event in the autocommand system, delete the above-defined extra excluded
" regions from delimitMate's state (the deletion being idempotent and
" having no effect if the extra excluded regions are not present in the
" targeted part of delimitMate's state).
autocmd User <buffer>
\ if expand('<afile>') ==# 'delimitMate_unmap'
\| let b:delimitMate_excluded_regions = substitute(
\ delimitMate#Get("excluded_regions"),
\ '\C\V' . s:delimitMate_extra_excluded_regions,
\ '', 'g')
\|endif
endif endif
if has("folding") && exists('g:rust_fold') && g:rust_fold != 0 if has("folding") && exists('g:rust_fold') && g:rust_fold != 0
@ -67,7 +96,7 @@ if has("folding") && exists('g:rust_fold') && g:rust_fold != 0
endif endif
endif endif
if has('conceal') && exists('g:rust_conceal') if has('conceal') && exists('g:rust_conceal') && g:rust_conceal != 0
let b:rust_set_conceallevel=1 let b:rust_set_conceallevel=1
setlocal conceallevel=2 setlocal conceallevel=2
endif endif
@ -85,16 +114,25 @@ onoremap <silent> <buffer> ]] :call rust#Jump('o', 'Forward')<CR>
" Commands {{{1 " Commands {{{1
" See |:RustRun| for docs " See |:RustRun| for docs
command! -nargs=* -complete=file -bang -bar -buffer RustRun call rust#Run(<bang>0, [<f-args>]) command! -nargs=* -complete=file -bang -buffer RustRun call rust#Run(<bang>0, <q-args>)
" See |:RustExpand| for docs " See |:RustExpand| for docs
command! -nargs=* -complete=customlist,rust#CompleteExpand -bang -bar -buffer RustExpand call rust#Expand(<bang>0, [<f-args>]) command! -nargs=* -complete=customlist,rust#CompleteExpand -bang -buffer RustExpand call rust#Expand(<bang>0, <q-args>)
" See |:RustEmitIr| for docs " See |:RustEmitIr| for docs
command! -nargs=* -bar -buffer RustEmitIr call rust#Emit("ir", [<f-args>]) command! -nargs=* -buffer RustEmitIr call rust#Emit("llvm-ir", <q-args>)
" See |:RustEmitAsm| for docs " See |:RustEmitAsm| for docs
command! -nargs=* -bar -buffer RustEmitAsm call rust#Emit("asm", [<f-args>]) command! -nargs=* -buffer RustEmitAsm call rust#Emit("asm", <q-args>)
" See |:RustPlay| for docs
command! -range=% RustPlay :call rust#Play(<count>, <line1>, <line2>, <f-args>)
" See |:RustFmt| for docs
command! -buffer RustFmt call rustfmt#Format()
" See |:RustFmtRange| for docs
command! -range -buffer RustFmtRange call rustfmt#FormatRange(<line1>, <line2>)
" Mappings {{{1 " Mappings {{{1
@ -132,6 +170,7 @@ let b:undo_ftplugin = "
\|delcommand RustExpand \|delcommand RustExpand
\|delcommand RustEmitIr \|delcommand RustEmitIr
\|delcommand RustEmitAsm \|delcommand RustEmitAsm
\|delcommand RustPlay
\|nunmap <buffer> <D-r> \|nunmap <buffer> <D-r>
\|nunmap <buffer> <D-R> \|nunmap <buffer> <D-R>
\|nunmap <buffer> [[ \|nunmap <buffer> [[
@ -140,11 +179,24 @@ let b:undo_ftplugin = "
\|xunmap <buffer> ]] \|xunmap <buffer> ]]
\|ounmap <buffer> [[ \|ounmap <buffer> [[
\|ounmap <buffer> ]] \|ounmap <buffer> ]]
\|set matchpairs-=<:>
\|unlet b:match_skip
\" \"
" }}}1 " }}}1
" Code formatting on save
if get(g:, "rustfmt_autosave", 0)
autocmd BufWritePre *.rs silent! call rustfmt#Format()
endif
augroup END
set matchpairs+=<:>
" For matchit.vim (rustArrow stops `Fn() -> X` messing things up)
let b:match_skip = 's:comment\|string\|rustArrow'
let &cpo = s:save_cpo let &cpo = s:save_cpo
unlet s:save_cpo unlet s:save_cpo
" vim: set noet sw=4 ts=4: " vim: set noet sw=8 ts=8:

View File

@ -1,11 +1,12 @@
" Vim indent file " Vim indent file
" Language: Rust " Language: Rust
" Author: Chris Morgan <me@chrismorgan.info> " Author: Chris Morgan <me@chrismorgan.info>
" Last Change: 2014 Sep 13 " Last Change: 2017 Mar 21
" For bugs, patches and license go to https://github.com/rust-lang/rust.vim
" Only load this indent file when no other was loaded. " Only load this indent file when no other was loaded.
if exists("b:did_indent") if exists("b:did_indent")
finish finish
endif endif
let b:did_indent = 1 let b:did_indent = 1
@ -13,7 +14,7 @@ setlocal cindent
setlocal cinoptions=L0,(0,Ws,J1,j1 setlocal cinoptions=L0,(0,Ws,J1,j1
setlocal cinkeys=0{,0},!^F,o,O,0[,0] setlocal cinkeys=0{,0},!^F,o,O,0[,0]
" Don't think cinwords will actually do anything at all... never mind " Don't think cinwords will actually do anything at all... never mind
setlocal cinwords=for,if,else,while,loop,impl,mod,unsafe,trait,struct,enum,fn,extern setlocal cinwords=for,if,else,while,loop,impl,mod,unsafe,trait,struct,enum,fn,extern,macro
" Some preliminary settings " Some preliminary settings
setlocal nolisp " Make sure lisp indenting doesn't supersede us setlocal nolisp " Make sure lisp indenting doesn't supersede us
@ -25,9 +26,12 @@ setlocal indentexpr=GetRustIndent(v:lnum)
" Only define the function once. " Only define the function once.
if exists("*GetRustIndent") if exists("*GetRustIndent")
finish finish
endif endif
let s:save_cpo = &cpo
set cpo&vim
" Come here when loading the script the first time. " Come here when loading the script the first time.
function! s:get_line_trimmed(lnum) function! s:get_line_trimmed(lnum)
@ -121,10 +125,18 @@ function GetRustIndent(lnum)
let prevlinenum = prevnonblank(prevlinenum - 1) let prevlinenum = prevnonblank(prevlinenum - 1)
let prevline = s:get_line_trimmed(prevlinenum) let prevline = s:get_line_trimmed(prevlinenum)
endwhile endwhile
" Handle where clauses nicely: subsequent values should line up nicely.
if prevline[len(prevline) - 1] == ","
\ && prevline =~# '^\s*where\s'
return indent(prevlinenum) + 6
endif
if prevline[len(prevline) - 1] == "," if prevline[len(prevline) - 1] == ","
\ && s:get_line_trimmed(a:lnum) !~ '^\s*[\[\]{}]' \ && s:get_line_trimmed(a:lnum) !~ '^\s*[\[\]{}]'
\ && prevline !~ '^\s*fn\s' \ && prevline !~ '^\s*fn\s'
\ && prevline !~ '([^()]\+,$' \ && prevline !~ '([^()]\+,$'
\ && s:get_line_trimmed(a:lnum) !~ '^\s*\S\+\s*=>'
" Oh ho! The previous line ended in a comma! I bet cindent will try to " Oh ho! The previous line ended in a comma! I bet cindent will try to
" take this too far... For now, let's normally use the previous line's " take this too far... For now, let's normally use the previous line's
" indent. " indent.
@ -149,6 +161,8 @@ function GetRustIndent(lnum)
" if baz && (foo || " if baz && (foo ||
" bar) { " bar) {
" "
" Another case is when the current line is a new match arm.
"
" There are probably other cases where we don't want to do this as " There are probably other cases where we don't want to do this as
" well. Add them as needed. " well. Add them as needed.
return indent(prevlinenum) return indent(prevlinenum)
@ -194,3 +208,6 @@ function GetRustIndent(lnum)
" Fall back on cindent, which does it mostly right " Fall back on cindent, which does it mostly right
return cindent(a:lnum) return cindent(a:lnum)
endfunction endfunction
let &cpo = s:save_cpo
unlet s:save_cpo

View File

@ -20,3 +20,17 @@ endif
let &cpo = s:save_cpo let &cpo = s:save_cpo
unlet s:save_cpo unlet s:save_cpo
command! -nargs=* Cargo call cargo#cmd(<q-args>)
command! -nargs=* Cbuild call cargo#build(<q-args>)
command! -nargs=* Cclean call cargo#clean(<q-args>)
command! -nargs=* Cdoc call cargo#doc(<q-args>)
command! -nargs=* Cnew call cargo#new(<q-args>)
command! -nargs=* Cinit call cargo#init(<q-args>)
command! -nargs=* Crun call cargo#run(<q-args>)
command! -nargs=* Ctest call cargo#test(<q-args>)
command! -nargs=* Cbench call cargo#bench(<q-args>)
command! -nargs=* Cupdate call cargo#update(<q-args>)
command! -nargs=* Csearch call cargo#search(<q-args>)
command! -nargs=* Cpublish call cargo#publish(<q-args>)
command! -nargs=* Cinstall call cargo#install(<q-args>)

View File

@ -3,17 +3,23 @@
" Maintainer: Patrick Walton <pcwalton@mozilla.com> " Maintainer: Patrick Walton <pcwalton@mozilla.com>
" Maintainer: Ben Blum <bblum@cs.cmu.edu> " Maintainer: Ben Blum <bblum@cs.cmu.edu>
" Maintainer: Chris Morgan <me@chrismorgan.info> " Maintainer: Chris Morgan <me@chrismorgan.info>
" Last Change: January 5, 2015 " Last Change: Feb 24, 2016
" For bugs, patches and license go to https://github.com/rust-lang/rust.vim
if version < 600 if version < 600
syntax clear syntax clear
elseif exists("b:current_syntax") elseif exists("b:current_syntax")
finish finish
endif endif
" Syntax definitions {{{1 " Syntax definitions {{{1
" Basic keywords {{{2 " Basic keywords {{{2
syn keyword rustConditional match if else syn keyword rustConditional match if else
syn keyword rustRepeat for loop while
syn keyword rustTypedef type nextgroup=rustIdentifier skipwhite skipempty
syn keyword rustStructure struct enum nextgroup=rustIdentifier skipwhite skipempty
syn keyword rustUnion union nextgroup=rustIdentifier skipwhite skipempty contained
syn match rustUnionContextual /\<union\_s\+\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*/ transparent contains=rustUnion
syn keyword rustOperator as syn keyword rustOperator as
syn match rustAssert "\<assert\(\w\)*!" contained syn match rustAssert "\<assert\(\w\)*!" contained
@ -23,17 +29,26 @@ syn keyword rustKeyword box nextgroup=rustBoxPlacement skipwhite skipempty
syn keyword rustKeyword continue syn keyword rustKeyword continue
syn keyword rustKeyword extern nextgroup=rustExternCrate,rustObsoleteExternMod skipwhite skipempty syn keyword rustKeyword extern nextgroup=rustExternCrate,rustObsoleteExternMod skipwhite skipempty
syn keyword rustKeyword fn nextgroup=rustFuncName skipwhite skipempty syn keyword rustKeyword fn nextgroup=rustFuncName skipwhite skipempty
syn keyword rustKeyword for in if impl let syn keyword rustKeyword in impl let
syn keyword rustKeyword loop once pub syn keyword rustKeyword macro
syn keyword rustKeyword return super syn keyword rustKeyword pub nextgroup=rustPubScope skipwhite skipempty
syn keyword rustKeyword unsafe virtual where while syn keyword rustKeyword return
syn keyword rustKeyword yield
syn keyword rustSuper super
syn keyword rustKeyword where
syn keyword rustUnsafeKeyword unsafe
syn keyword rustKeyword use nextgroup=rustModPath skipwhite skipempty syn keyword rustKeyword use nextgroup=rustModPath skipwhite skipempty
" FIXME: Scoped impl's name is also fallen in this category " FIXME: Scoped impl's name is also fallen in this category
syn keyword rustKeyword mod trait struct enum type nextgroup=rustIdentifier skipwhite skipempty syn keyword rustKeyword mod trait nextgroup=rustIdentifier skipwhite skipempty
syn keyword rustStorage move mut ref static const syn keyword rustStorage move mut ref static const
syn match rustDefault /\<default\ze\_s\+\(impl\|fn\|type\|const\)\>/
syn keyword rustInvalidBareKeyword crate syn keyword rustInvalidBareKeyword crate
syn keyword rustPubScopeCrate crate contained
syn match rustPubScopeDelim /[()]/ contained
syn match rustPubScope /([^()]*)/ contained contains=rustPubScopeDelim,rustPubScopeCrate,rustSuper,rustModPath,rustModPathSep,rustSelf transparent
syn keyword rustExternCrate crate contained nextgroup=rustIdentifier,rustExternCrateString skipwhite skipempty syn keyword rustExternCrate crate contained nextgroup=rustIdentifier,rustExternCrateString skipwhite skipempty
" This is to get the `bar` part of `extern crate "foo" as bar;` highlighting. " This is to get the `bar` part of `extern crate "foo" as bar;` highlighting.
syn match rustExternCrateString /".*"\_s*as/ contained nextgroup=rustIdentifier skipwhite transparent skipempty contains=rustString,rustOperator syn match rustExternCrateString /".*"\_s*as/ contained nextgroup=rustIdentifier skipwhite transparent skipempty contains=rustString,rustOperator
@ -43,7 +58,6 @@ syn match rustIdentifier contains=rustIdentifierPrime "\%([^[:cntrl:][:spac
syn match rustFuncName "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained syn match rustFuncName "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained
syn region rustBoxPlacement matchgroup=rustBoxPlacementParens start="(" end=")" contains=TOP contained syn region rustBoxPlacement matchgroup=rustBoxPlacementParens start="(" end=")" contains=TOP contained
syn keyword rustBoxPlacementExpr GC containedin=rustBoxPlacement
" Ideally we'd have syntax rules set up to match arbitrary expressions. Since " Ideally we'd have syntax rules set up to match arbitrary expressions. Since
" we don't, we'll just define temporary contained rules to handle balancing " we don't, we'll just define temporary contained rules to handle balancing
" delimiters. " delimiters.
@ -56,13 +70,13 @@ syn match rustMacroRepeatCount ".\?[*+]" contained
syn match rustMacroVariable "$\w\+" syn match rustMacroVariable "$\w\+"
" Reserved (but not yet used) keywords {{{2 " Reserved (but not yet used) keywords {{{2
syn keyword rustReservedKeyword alignof be do offsetof priv pure sizeof typeof unsized yield abstract final override macro syn keyword rustReservedKeyword alignof become do offsetof priv pure sizeof typeof unsized abstract virtual final override
" Built-in types {{{2 " Built-in types {{{2
syn keyword rustType isize usize float char bool u8 u16 u32 u64 f32 syn keyword rustType isize usize char bool u8 u16 u32 u64 u128 f32
syn keyword rustType f64 i8 i16 i32 i64 str Self syn keyword rustType f64 i8 i16 i32 i64 i128 str Self
" Things from the prelude (src/libstd/prelude.rs) {{{2 " Things from the libstd v1 prelude (src/libstd/prelude/v1.rs) {{{2
" This section is just straight transformation of the contents of the prelude, " This section is just straight transformation of the contents of the prelude,
" to make it easy to update. " to make it easy to update.
@ -71,30 +85,27 @@ syn keyword rustTrait Copy Send Sized Sync
syn keyword rustTrait Drop Fn FnMut FnOnce syn keyword rustTrait Drop Fn FnMut FnOnce
" Reexported functions {{{3 " Reexported functions {{{3
syn keyword rustFunction drop " Theres no point in highlighting these; when one writes drop( or drop::< it
" gets the same highlighting anyway, and if someone writes `let drop = …;` we
" dont really want *that* drop to be highlighted.
"syn keyword rustFunction drop
" Reexported types and traits {{{3 " Reexported types and traits {{{3
syn keyword rustTrait Box syn keyword rustTrait Box
syn keyword rustTrait CharExt syn keyword rustTrait ToOwned
syn keyword rustTrait Clone syn keyword rustTrait Clone
syn keyword rustTrait PartialEq PartialOrd Eq Ord syn keyword rustTrait PartialEq PartialOrd Eq Ord
syn keyword rustTrait DoubleEndedIterator syn keyword rustTrait AsRef AsMut Into From
syn keyword rustTrait ExactSizeIterator syn keyword rustTrait Default
syn keyword rustTrait Iterator IteratorExt Extend syn keyword rustTrait Iterator Extend IntoIterator
syn keyword rustTrait DoubleEndedIterator ExactSizeIterator
syn keyword rustEnum Option syn keyword rustEnum Option
syn keyword rustEnumVariant Some None syn keyword rustEnumVariant Some None
syn keyword rustTrait PtrExt MutPtrExt
syn keyword rustEnum Result syn keyword rustEnum Result
syn keyword rustEnumVariant Ok Err syn keyword rustEnumVariant Ok Err
syn keyword rustTrait AsSlice syn keyword rustTrait SliceConcatExt
syn keyword rustTrait SliceExt SliceConcatExt
syn keyword rustTrait Str StrExt
syn keyword rustTrait String ToString syn keyword rustTrait String ToString
syn keyword rustTrait Vec syn keyword rustTrait Vec
" FIXME: remove when path reform lands
syn keyword rustTrait Path GenericPath
" FIXME: remove when I/O reform lands
syn keyword rustTrait Buffer Writer Reader Seek BufferPrelude
" Other syntax {{{2 " Other syntax {{{2
syn keyword rustSelf self syn keyword rustSelf self
@ -120,27 +131,33 @@ syn match rustSigil display /[&~@*][^)= \t\r\n]/he=e-1,me=e-1
" This isn't actually correct; a closure with no arguments can be `|| { }`. " This isn't actually correct; a closure with no arguments can be `|| { }`.
" Last, because the & in && isn't a sigil " Last, because the & in && isn't a sigil
syn match rustOperator display "&&\|||" syn match rustOperator display "&&\|||"
" This is rustArrowCharacter rather than rustArrow for the sake of matchparen,
" so it skips the ->; see http://stackoverflow.com/a/30309949 for details.
syn match rustArrowCharacter display "->"
syn match rustQuestionMark display "?\([a-zA-Z]\+\)\@!"
syn match rustMacro '\w\(\w\)*!' contains=rustAssert,rustPanic syn match rustMacro '\w\(\w\)*!' contains=rustAssert,rustPanic
syn match rustMacro '#\w\(\w\)*' contains=rustAssert,rustPanic syn match rustMacro '#\w\(\w\)*' contains=rustAssert,rustPanic
syn match rustEscapeError display contained /\\./ syn match rustEscapeError display contained /\\./
syn match rustEscape display contained /\\\([nrt0\\'"]\|x\x\{2}\)/ syn match rustEscape display contained /\\\([nrt0\\'"]\|x\x\{2}\)/
syn match rustEscapeUnicode display contained /\\\(u\x\{4}\|U\x\{8}\)/ syn match rustEscapeUnicode display contained /\\u{\%(\x_*\)\{1,6}}/
syn match rustEscapeUnicode display contained /\\u{\x\{1,6}}/
syn match rustStringContinuation display contained /\\\n\s*/ syn match rustStringContinuation display contained /\\\n\s*/
syn region rustString start=+b"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeError,rustStringContinuation syn region rustString start=+b"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeError,rustStringContinuation
syn region rustString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustStringContinuation,@Spell syn region rustString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustStringContinuation,@Spell
syn region rustString start='b\?r\z(#*\)"' end='"\z1' contains=@Spell syn region rustString start='b\?r\z(#*\)"' end='"\z1' contains=@Spell
syn region rustAttribute start="#!\?\[" end="\]" contains=rustString,rustDerive syn region rustAttribute start="#!\?\[" end="\]" contains=rustString,rustDerive,rustCommentLine,rustCommentBlock,rustCommentLineDocError,rustCommentBlockDocError
syn region rustDerive start="derive(" end=")" contained contains=rustTrait syn region rustDerive start="derive(" end=")" contained contains=rustDeriveTrait
" This list comes from src/libsyntax/ext/deriving/mod.rs
" Some are deprecated (Encodable, Decodable) or to be removed after a new snapshot (Show).
syn keyword rustDeriveTrait contained Clone Hash RustcEncodable RustcDecodable Encodable Decodable PartialEq Eq PartialOrd Ord Rand Show Debug Default FromPrimitive Send Sync Copy
" Number literals " Number literals
syn match rustDecNumber display "\<[0-9][0-9_]*\%([iu]\%(s\|8\|16\|32\|64\)\)\=" syn match rustDecNumber display "\<[0-9][0-9_]*\%([iu]\%(size\|8\|16\|32\|64\|128\)\)\="
syn match rustHexNumber display "\<0x[a-fA-F0-9_]\+\%([iu]\%(s\|8\|16\|32\|64\)\)\=" syn match rustHexNumber display "\<0x[a-fA-F0-9_]\+\%([iu]\%(size\|8\|16\|32\|64\|128\)\)\="
syn match rustOctNumber display "\<0o[0-7_]\+\%([iu]\%(s\|8\|16\|32\|64\)\)\=" syn match rustOctNumber display "\<0o[0-7_]\+\%([iu]\%(size\|8\|16\|32\|64\|128\)\)\="
syn match rustBinNumber display "\<0b[01_]\+\%([iu]\%(s\|8\|16\|32\|64\)\)\=" syn match rustBinNumber display "\<0b[01_]\+\%([iu]\%(size\|8\|16\|32\|64\|128\)\)\="
" Special case for numbers of the form "1." which are float literals, unless followed by " Special case for numbers of the form "1." which are float literals, unless followed by
" an identifier, which makes them integer literals with a method call or field access, " an identifier, which makes them integer literals with a method call or field access,
@ -154,24 +171,29 @@ syn match rustFloat display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\=\%([eE
syn match rustFloat display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\=\%([eE][+-]\=[0-9_]\+\)\=\(f32\|f64\)" syn match rustFloat display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\=\%([eE][+-]\=[0-9_]\+\)\=\(f32\|f64\)"
" For the benefit of delimitMate " For the benefit of delimitMate
syn region rustLifetimeCandidate display start=/&'\%(\([^'\\]\|\\\(['nrt0\\\"]\|x\x\{2}\|u\x\{4}\|U\x\{8}\)\)'\)\@!/ end=/[[:cntrl:][:space:][:punct:]]\@=\|$/ contains=rustSigil,rustLifetime syn region rustLifetimeCandidate display start=/&'\%(\([^'\\]\|\\\(['nrt0\\\"]\|x\x\{2}\|u{\%(\x_*\)\{1,6}}\)\)'\)\@!/ end=/[[:cntrl:][:space:][:punct:]]\@=\|$/ contains=rustSigil,rustLifetime
syn region rustGenericRegion display start=/<\%('\|[^[cntrl:][:space:][:punct:]]\)\@=')\S\@=/ end=/>/ contains=rustGenericLifetimeCandidate syn region rustGenericRegion display start=/<\%('\|[^[cntrl:][:space:][:punct:]]\)\@=')\S\@=/ end=/>/ contains=rustGenericLifetimeCandidate
syn region rustGenericLifetimeCandidate display start=/\%(<\|,\s*\)\@<='/ end=/[[:cntrl:][:space:][:punct:]]\@=\|$/ contains=rustSigil,rustLifetime syn region rustGenericLifetimeCandidate display start=/\%(<\|,\s*\)\@<='/ end=/[[:cntrl:][:space:][:punct:]]\@=\|$/ contains=rustSigil,rustLifetime
"rustLifetime must appear before rustCharacter, or chars will get the lifetime highlighting "rustLifetime must appear before rustCharacter, or chars will get the lifetime highlighting
syn match rustLifetime display "\'\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" syn match rustLifetime display "\'\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*"
syn match rustLabel display "\'\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*:"
syn match rustCharacterInvalid display contained /b\?'\zs[\n\r\t']\ze'/ syn match rustCharacterInvalid display contained /b\?'\zs[\n\r\t']\ze'/
" The groups negated here add up to 0-255 but nothing else (they do not seem to go beyond ASCII). " The groups negated here add up to 0-255 but nothing else (they do not seem to go beyond ASCII).
syn match rustCharacterInvalidUnicode display contained /b'\zs[^[:cntrl:][:graph:][:alnum:][:space:]]\ze'/ syn match rustCharacterInvalidUnicode display contained /b'\zs[^[:cntrl:][:graph:][:alnum:][:space:]]\ze'/
syn match rustCharacter /b'\([^\\]\|\\\(.\|x\x\{2}\)\)'/ contains=rustEscape,rustEscapeError,rustCharacterInvalid,rustCharacterInvalidUnicode syn match rustCharacter /b'\([^\\]\|\\\(.\|x\x\{2}\)\)'/ contains=rustEscape,rustEscapeError,rustCharacterInvalid,rustCharacterInvalidUnicode
syn match rustCharacter /'\([^\\]\|\\\(.\|x\x\{2}\|u\x\{4}\|U\x\{8}\|u{\x\{1,6}}\)\)'/ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustCharacterInvalid syn match rustCharacter /'\([^\\]\|\\\(.\|x\x\{2}\|u{\%(\x_*\)\{1,6}}\)\)'/ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustCharacterInvalid
syn region rustCommentLine start="//" end="$" contains=rustTodo,@Spell syn match rustShebang /\%^#![^[].*/
syn region rustCommentLineDoc start="//\%(//\@!\|!\)" end="$" contains=rustTodo,@Spell syn region rustCommentLine start="//" end="$" contains=rustTodo,@Spell
syn region rustCommentBlock matchgroup=rustCommentBlock start="/\*\%(!\|\*[*/]\@!\)\@!" end="\*/" contains=rustTodo,rustCommentBlockNest,@Spell syn region rustCommentLineDoc start="//\%(//\@!\|!\)" end="$" contains=rustTodo,@Spell
syn region rustCommentBlockDoc matchgroup=rustCommentBlockDoc start="/\*\%(!\|\*[*/]\@!\)" end="\*/" contains=rustTodo,rustCommentBlockDocNest,@Spell syn region rustCommentLineDocError start="//\%(//\@!\|!\)" end="$" contains=rustTodo,@Spell contained
syn region rustCommentBlockNest matchgroup=rustCommentBlock start="/\*" end="\*/" contains=rustTodo,rustCommentBlockNest,@Spell contained transparent syn region rustCommentBlock matchgroup=rustCommentBlock start="/\*\%(!\|\*[*/]\@!\)\@!" end="\*/" contains=rustTodo,rustCommentBlockNest,@Spell
syn region rustCommentBlockDocNest matchgroup=rustCommentBlockDoc start="/\*" end="\*/" contains=rustTodo,rustCommentBlockDocNest,@Spell contained transparent syn region rustCommentBlockDoc matchgroup=rustCommentBlockDoc start="/\*\%(!\|\*[*/]\@!\)" end="\*/" contains=rustTodo,rustCommentBlockDocNest,@Spell
syn region rustCommentBlockDocError matchgroup=rustCommentBlockDocError start="/\*\%(!\|\*[*/]\@!\)" end="\*/" contains=rustTodo,rustCommentBlockDocNestError,@Spell contained
syn region rustCommentBlockNest matchgroup=rustCommentBlock start="/\*" end="\*/" contains=rustTodo,rustCommentBlockNest,@Spell contained transparent
syn region rustCommentBlockDocNest matchgroup=rustCommentBlockDoc start="/\*" end="\*/" contains=rustTodo,rustCommentBlockDocNest,@Spell contained transparent
syn region rustCommentBlockDocNestError matchgroup=rustCommentBlockDocError start="/\*" end="\*/" contains=rustTodo,rustCommentBlockDocNestError,@Spell contained transparent
" FIXME: this is a really ugly and not fully correct implementation. Most " FIXME: this is a really ugly and not fully correct implementation. Most
" importantly, a case like ``/* */*`` should have the final ``*`` not being in " importantly, a case like ``/* */*`` should have the final ``*`` not being in
" a comment, but in practice at present it leaves comments open two levels " a comment, but in practice at present it leaves comments open two levels
@ -198,6 +220,7 @@ hi def link rustOctNumber rustNumber
hi def link rustBinNumber rustNumber hi def link rustBinNumber rustNumber
hi def link rustIdentifierPrime rustIdentifier hi def link rustIdentifierPrime rustIdentifier
hi def link rustTrait rustType hi def link rustTrait rustType
hi def link rustDeriveTrait rustTrait
hi def link rustMacroRepeatCount rustMacroRepeatDelimiters hi def link rustMacroRepeatCount rustMacroRepeatDelimiters
hi def link rustMacroRepeatDelimiters Macro hi def link rustMacroRepeatDelimiters Macro
@ -218,9 +241,18 @@ hi def link rustEnumVariant rustConstant
hi def link rustConstant Constant hi def link rustConstant Constant
hi def link rustSelf Constant hi def link rustSelf Constant
hi def link rustFloat Float hi def link rustFloat Float
hi def link rustArrowCharacter rustOperator
hi def link rustOperator Operator hi def link rustOperator Operator
hi def link rustKeyword Keyword hi def link rustKeyword Keyword
hi def link rustTypedef Keyword " More precise is Typedef, but it doesn't feel right for Rust
hi def link rustStructure Keyword " More precise is Structure
hi def link rustUnion rustStructure
hi def link rustPubScopeDelim Delimiter
hi def link rustPubScopeCrate rustKeyword
hi def link rustSuper rustKeyword
hi def link rustUnsafeKeyword Exception
hi def link rustReservedKeyword Error hi def link rustReservedKeyword Error
hi def link rustRepeat Conditional
hi def link rustConditional Conditional hi def link rustConditional Conditional
hi def link rustIdentifier Identifier hi def link rustIdentifier Identifier
hi def link rustCapsIdent rustIdentifier hi def link rustCapsIdent rustIdentifier
@ -229,10 +261,13 @@ hi def link rustModPathSep Delimiter
hi def link rustFunction Function hi def link rustFunction Function
hi def link rustFuncName Function hi def link rustFuncName Function
hi def link rustFuncCall Function hi def link rustFuncCall Function
hi def link rustShebang Comment
hi def link rustCommentLine Comment hi def link rustCommentLine Comment
hi def link rustCommentLineDoc SpecialComment hi def link rustCommentLineDoc SpecialComment
hi def link rustCommentLineDocError Error
hi def link rustCommentBlock rustCommentLine hi def link rustCommentBlock rustCommentLine
hi def link rustCommentBlockDoc rustCommentLineDoc hi def link rustCommentBlockDoc rustCommentLineDoc
hi def link rustCommentBlockDocError Error
hi def link rustAssert PreCondit hi def link rustAssert PreCondit
hi def link rustPanic PreCondit hi def link rustPanic PreCondit
hi def link rustMacro Macro hi def link rustMacro Macro
@ -240,14 +275,16 @@ hi def link rustType Type
hi def link rustTodo Todo hi def link rustTodo Todo
hi def link rustAttribute PreProc hi def link rustAttribute PreProc
hi def link rustDerive PreProc hi def link rustDerive PreProc
hi def link rustDefault StorageClass
hi def link rustStorage StorageClass hi def link rustStorage StorageClass
hi def link rustObsoleteStorage Error hi def link rustObsoleteStorage Error
hi def link rustLifetime Special hi def link rustLifetime Special
hi def link rustLabel Label
hi def link rustInvalidBareKeyword Error hi def link rustInvalidBareKeyword Error
hi def link rustExternCrate rustKeyword hi def link rustExternCrate rustKeyword
hi def link rustObsoleteExternMod Error hi def link rustObsoleteExternMod Error
hi def link rustBoxPlacementParens Delimiter hi def link rustBoxPlacementParens Delimiter
hi def link rustBoxPlacementExpr rustKeyword hi def link rustQuestionMark Special
" Other Suggestions: " Other Suggestions:
" hi rustAttribute ctermfg=cyan " hi rustAttribute ctermfg=cyan

View File

@ -0,0 +1,53 @@
" Vim syntastic plugin
" Language: Rust
" Maintainer: Julien Levesy <jlevesy@gmail.com>
"
" See for details on how to add an external Syntastic checker:
" https://github.com/scrooloose/syntastic/wiki/Syntax-Checker-Guide#external
if exists("g:loaded_syntastic_rust_cargo_checker")
finish
endif
let g:loaded_syntastic_rust_cargo_checker = 1
" Force syntastic to call cargo without a specific file name
let g:syntastic_rust_cargo_fname = ""
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_rust_cargo_IsAvailable() dict
return executable(self.getExec()) &&
\ syntastic#util#versionIsAtLeast(self.getVersion(), [0, 16, 0])
endfunction
function! SyntaxCheckers_rust_cargo_GetLocList() dict
let makeprg = self.makeprgBuild({ "args": "check" })
" Ignored patterns, and blank lines
let errorformat =
\ '%-G,' .
\ '%-Gerror: aborting %.%#,' .
\ '%-Gerror: Could not compile %.%#,'
" Meaningful lines (errors, notes, warnings, contextual information)
let errorformat .=
\ '%Eerror: %m,' .
\ '%Eerror[E%n]: %m,' .
\ '%Wwarning: %m,' .
\ '%Inote: %m,' .
\ '%C %#--> %f:%l:%c'
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'cwd': expand('%:p:h'),
\ 'errorformat': errorformat })
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'rust',
\ 'name': 'cargo'})
let &cpo = s:save_cpo
unlet s:save_cpo

View File

@ -14,13 +14,26 @@ let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! SyntaxCheckers_rust_rustc_GetLocList() dict function! SyntaxCheckers_rust_rustc_GetLocList() dict
let makeprg = self.makeprgBuild({ 'args': '-Zparse-only' }) let makeprg = self.makeprgBuild({})
" Old errorformat (before nightly 2016/08/10)
let errorformat = let errorformat =
\ '%E%f:%l:%c: %\d%#:%\d%# %.%\{-}error:%.%\{-} %m,' . \ '%E%f:%l:%c: %\d%#:%\d%# %.%\{-}error:%.%\{-} %m,' .
\ '%W%f:%l:%c: %\d%#:%\d%# %.%\{-}warning:%.%\{-} %m,' . \ '%W%f:%l:%c: %\d%#:%\d%# %.%\{-}warning:%.%\{-} %m,' .
\ '%C%f:%l %m,' . \ '%C%f:%l %m'
\ '%-Z%.%#'
" New errorformat (after nightly 2016/08/10)
let errorformat .=
\ ',' .
\ '%-G,' .
\ '%-Gerror: aborting %.%#,' .
\ '%-Gerror: Could not compile %.%#,' .
\ '%Eerror: %m,' .
\ '%Eerror[E%n]: %m,' .
\ '%-Gwarning: the option `Z` is unstable %.%#,' .
\ '%Wwarning: %m,' .
\ '%Inote: %m,' .
\ '%C %#--> %f:%l:%c'
return SyntasticMake({ return SyntasticMake({
\ 'makeprg': makeprg, \ 'makeprg': makeprg,

View File

@ -54,6 +54,7 @@ lightline.vim https://github.com/itchyny/lightline.vim
lightline-ale https://github.com/maximbaz/lightline-ale lightline-ale https://github.com/maximbaz/lightline-ale
vim-abolish https://github.com/tpope/tpope-vim-abolish vim-abolish https://github.com/tpope/tpope-vim-abolish
mru.vim https://github.com/vim-scripts/mru.vim mru.vim https://github.com/vim-scripts/mru.vim
rust.vim https://github.com/rust-lang/rust.vim
vim-markdown https://github.com/plasticboy/vim-markdown vim-markdown https://github.com/plasticboy/vim-markdown
comfortable-motion.vim https://github.com/yuttie/comfortable-motion.vim comfortable-motion.vim https://github.com/yuttie/comfortable-motion.vim
gist-vim https://github.com/mattn/gist-vim gist-vim https://github.com/mattn/gist-vim

View File

@ -50,7 +50,7 @@ nmap <leader>w :w!<cr>
" :W sudo saves the file " :W sudo saves the file
" (useful for handling the permission-denied error) " (useful for handling the permission-denied error)
command W w !sudo tee % > /dev/null command! W w !sudo tee % > /dev/null
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""