1
0
Fork 0
mirror of synced 2024-12-21 06:21:07 -05:00

Updated plugins and added vim-abolish

This commit is contained in:
amix 2017-05-26 11:30:32 +02:00
parent 85e105159e
commit 48a2c325c3
38 changed files with 1876 additions and 288 deletions

View file

@ -2,22 +2,22 @@
Run your favorite search tool from Vim, with an enhanced results list. Run your favorite search tool from Vim, with an enhanced results list.
This plugin was designed as a Vim frontend for the Perl module [App::Ack]. Ack This plugin was designed as a Vim frontend for the programmer's search tool
can be used as a replacement for 99% of the uses of _grep_. The plugin allows [ack]. ack can be used as a replacement for 99% of the uses of `grep`. The
you to run ack from Vim, and shows the results in a split window. plugin allows you to search with ack from within Vim and shows the results in a
split window.
But here's a little secret for the Vim-seasoned: it's just a light wrapper for But here's a little secret for the Vim-seasoned: it's just a light wrapper for
Vim's [grepprg] and the [quickfix] window for match results. This makes it easy Vim's [grepprg] and the [quickfix] window for match results. This makes it easy
to integrate with your own Vim configuration and use existing knowledge of core to integrate with your own Vim configuration and use existing knowledge of core
features. It also means the plugin is flexible to use with other search tools. features. It also means the plugin is flexible to use with other search tools.
[App::Ack]: http://search.cpan.org/~petdance/ack/ack
[grepprg]: http://vimdoc.sourceforge.net/htmldoc/options.html#'grepprg' [grepprg]: http://vimdoc.sourceforge.net/htmldoc/options.html#'grepprg'
[quickfix]: http://vimdoc.sourceforge.net/htmldoc/quickfix.html#quickfix [quickfix]: http://vimdoc.sourceforge.net/htmldoc/quickfix.html#quickfix
## Installation ## Installation
### Ack ### ack
You will need ack (>= 2.0), of course. To install it follow the You will need ack (>= 2.0), of course. To install it follow the
[manual](http://beyondgrep.com/install/). [manual](http://beyondgrep.com/install/).
@ -49,8 +49,6 @@ NeoBundle 'mileszs/ack.vim'
[Download][releases] the plugin and extract it in `~/.vim/` (or [Download][releases] the plugin and extract it in `~/.vim/` (or
`%PROGRAMFILES%/Vim/vimfiles` on Windows). `%PROGRAMFILES%/Vim/vimfiles` on Windows).
[zipball]: https://github.com/mileszs/ack.vim/archive/master.zip
## Usage ## Usage
:Ack [options] {pattern} [{directories}] :Ack [options] {pattern} [{directories}]
@ -60,7 +58,7 @@ for the `{pattern}`.
Files containing the search term will be listed in the quickfix window, along Files containing the search term will be listed in the quickfix window, along
with the line number of the occurrence, once for each occurrence. `<Enter>` on with the line number of the occurrence, once for each occurrence. `<Enter>` on
a line in this window will open the file, and place the cursor on the matching a line in this window will open the file and place the cursor on the matching
line. line.
Just like where you use `:grep`, `:grepadd`, `:lgrep`, and :`lgrepadd`, you can Just like where you use `:grep`, `:grepadd`, `:lgrep`, and :`lgrepadd`, you can
@ -140,22 +138,22 @@ the convention of Vim's built-in `:grep` and `:make` commands.
## Changelog ## Changelog
Please see [the Github releases page][releases]. Please see [the GitHub releases page][releases].
## Credits ## Credits
This plugin is derived from Antoine Imbert's blog post [Ack and Vim This plugin is derived from Antoine Imbert's blog post [ack and Vim
Integration][] (in particular, the function in the update to the post). [Miles Integration][] (in particular, the function in the update to the post). [Miles
Sterrett][mileszs] packaged it up as a plugin and documented it in Vim's help Sterrett][mileszs] packaged it up as a plugin and documented it in Vim's help
format, and since then [many contributors][contributors] have submitted format, and since then [many contributors][contributors] have submitted
enhancements and fixes. enhancements and fixes.
And of course, where would we be without [Ack]. And, you know, Vim. And of course, where would we be without [ack]. And, you know, Vim.
[Ack and Vim Integration]: http://blog.ant0ine.com/typepad/2007/03/ack-and-vim-integration.html [ack and Vim Integration]: http://blog.ant0ine.com/typepad/2007/03/ack-and-vim-integration.html
[mileszs]: https://github.com/mileszs [mileszs]: https://github.com/mileszs
[contributors]: https://github.com/mileszs/ack.vim/graphs/contributors [contributors]: https://github.com/mileszs/ack.vim/graphs/contributors
[Ack]: http://beyondgrep.com/ [ack]: http://beyondgrep.com/
[vim-dispatch]: https://github.com/tpope/vim-dispatch [vim-dispatch]: https://github.com/tpope/vim-dispatch
[releases]: https://github.com/mileszs/ack.vim/releases [releases]: https://github.com/mileszs/ack.vim/releases

View file

@ -39,7 +39,9 @@ if g:ctrlp_map != '' && !hasmapto('<plug>(ctrlp)')
exe 'map' g:ctrlp_map '<plug>(ctrlp)' exe 'map' g:ctrlp_map '<plug>(ctrlp)'
en en
cal ctrlp#mrufiles#init() if !exists('g:ctrlp_types') || index(g:ctrlp_types, 'mru') >= 0
cal ctrlp#mrufiles#init()
en
com! -bar CtrlPTag cal ctrlp#init(ctrlp#tag#id()) com! -bar CtrlPTag cal ctrlp#init(ctrlp#tag#id())
com! -bar CtrlPQuickfix cal ctrlp#init(ctrlp#quickfix#id()) com! -bar CtrlPQuickfix cal ctrlp#init(ctrlp#quickfix#id())

View file

@ -89,7 +89,9 @@ function! nerdtree#deprecated(func, ...)
endfunction endfunction
" FUNCTION: nerdtree#exec(cmd) {{{2 " FUNCTION: nerdtree#exec(cmd) {{{2
" same as :exec cmd but eventignore=all is set for the duration " Same as :exec cmd but with eventignore set for the duration
" to disable the autocommands used by NERDTree (BufEnter,
" BufLeave and VimEnter)
function! nerdtree#exec(cmd) function! nerdtree#exec(cmd)
let old_ei = &ei let old_ei = &ei
set ei=BufEnter,BufLeave,VimEnter set ei=BufEnter,BufLeave,VimEnter

View file

@ -806,7 +806,7 @@ then all files ending in .vim or ~ will be ignored.
There are 2 magic flags that can be appended to the end of each regular There are 2 magic flags that can be appended to the end of each regular
expression to specify that the regex should match only files or only dirs. expression to specify that the regex should match only files or only dirs.
These flags are "[[dir]]" and "[[file]]". Example: > These flags are "[[dir]]" and "[[file]]". Example: >
let NERDTreeIgnore=['.d$[[dir]]', '.o$[[file]]'] let NERDTreeIgnore=['\.d$[[dir]]', '\.o$[[file]]']
< <
This will cause all dirs ending in ".d" to be ignored and all files ending in This will cause all dirs ending in ".d" to be ignored and all files ending in
".o" to be ignored. ".o" to be ignored.

View file

@ -544,7 +544,7 @@ function! s:Path.readInfoFromDisk(fullpath)
throw "NERDTree.InvalidFiletypeError: Cant handle FIFO files: " . a:fullpath throw "NERDTree.InvalidFiletypeError: Cant handle FIFO files: " . a:fullpath
endif endif
let self.pathSegments = split(fullpath, '/') let self.pathSegments = filter(split(fullpath, '/'), '!empty(v:val)')
let self.isReadOnly = 0 let self.isReadOnly = 0
if isdirectory(a:fullpath) if isdirectory(a:fullpath)

View file

@ -4633,6 +4633,7 @@ The following checkers are available for PHP (filetype "php"):
2. PHP_CodeSniffer..........|syntastic-php-phpcs| 2. PHP_CodeSniffer..........|syntastic-php-phpcs|
3. PHPLint..................|syntastic-php-phplint| 3. PHPLint..................|syntastic-php-phplint|
4. PHP Mess Detector........|syntastic-php-phpmd| 4. PHP Mess Detector........|syntastic-php-phpmd|
5. PHPStan..................|syntastic-php-phpstan|
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
1. PHP *syntastic-php-php* 1. PHP *syntastic-php-php*
@ -4712,6 +4713,24 @@ Checker options~
This checker is initialised using the "makeprgBuild()" function and thus it This checker is initialised using the "makeprgBuild()" function and thus it
accepts the standard options described at |syntastic-config-makeprg|. accepts the standard options described at |syntastic-config-makeprg|.
------------------------------------------------------------------------------
5. PHP Static Analysis Tool *syntastic-php-phpstan*
Name: phpstan
Maintainer: Przepompownia <przepompownia@users.noreply.github.com>
"PHPStan" focuses on finding errors in your code without actually running it.
See the project's page iat GitHub for details:
https://github.com/phpstan/phpstan
Syntastic supports "PHPStan" versions 0.7 and later.
Checker options~
This checker is initialised using the "makeprgBuild()" function and thus it
accepts the standard options described at |syntastic-config-makeprg|.
============================================================================== ==============================================================================
SYNTAX CHECKERS FOR POD *syntastic-checkers-pod* SYNTAX CHECKERS FOR POD *syntastic-checkers-pod*
@ -6123,6 +6142,13 @@ Installation~
You can install "Slim-Lint" with "gem": > You can install "Slim-Lint" with "gem": >
gem install slim_lint gem install slim_lint
< <
Note~
You probably also need a plugin to set |filetype| for Slim files, such as
"vim-slim":
https://github.com/slim-template/vim-slim
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
2. Slimrb *syntastic-slim-slimrb* 2. Slimrb *syntastic-slim-slimrb*
@ -6139,6 +6165,13 @@ Checker options~
This checker is initialised using the "makeprgBuild()" function and thus it This checker is initialised using the "makeprgBuild()" function and thus it
accepts the standard options described at |syntastic-config-makeprg|. accepts the standard options described at |syntastic-config-makeprg|.
Note~
You probably also need a plugin to set |filetype| for Slim files, such as
"vim-slim":
https://github.com/slim-template/vim-slim
============================================================================== ==============================================================================
SYNTAX CHECKERS FOR SML *syntastic-checkers-sml* SYNTAX CHECKERS FOR SML *syntastic-checkers-sml*

View file

@ -19,7 +19,7 @@ if has('reltime')
lockvar! g:_SYNTASTIC_START lockvar! g:_SYNTASTIC_START
endif endif
let g:_SYNTASTIC_VERSION = '3.8.0-51' let g:_SYNTASTIC_VERSION = '3.8.0-55'
lockvar g:_SYNTASTIC_VERSION lockvar g:_SYNTASTIC_VERSION
" Sanity checks {{{1 " Sanity checks {{{1

View file

@ -20,8 +20,24 @@ set cpo&vim
function! SyntaxCheckers_go_gotype_GetLocList() dict function! SyntaxCheckers_go_gotype_GetLocList() dict
let buf = bufnr('') let buf = bufnr('')
if !exists('s:go_new')
let command = syntastic#util#shescape(syntastic#util#bufVar(buf, 'go_go_exec', 'go')) . ' version'
let version_output = syntastic#util#system(command)
call self.log('finding go version: ' . string(command) . ': ' .
\ string(split(version_output, "\n", 1)) .
\ (v:shell_error ? ' (exit code ' . v:shell_error . ')' : ''))
let parsed_ver = syntastic#util#parseVersion(version_output)
if len(parsed_ver)
let s:go_new = syntastic#util#versionIsAtLeast(parsed_ver, [1, 8])
else
call syntastic#log#error("checker " . self.getCName() . ": can't parse go version (abnormal termination?)")
return []
endif
endif
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'args': (bufname(buf) =~# '\m_test\.go$' ? '-a' : ''), \ 'args': (bufname(buf) =~# '\m_test\.go$' ? (s:go_new ? '-t' : '-a') : ''),
\ 'fname': '.' }) \ 'fname': '.' })
let errorformat = let errorformat =

View file

@ -0,0 +1,49 @@
"============================================================================
"File: phpstan.vim
"Description: Syntax checking plugin for syntastic
"Maintainer: Przepompownia przepompownia@users.noreply.github.com
"License: This program is free software. It comes without any warranty,
" to the extent permitted by applicable law. You can redistribute
" it and/or modify it under the terms of the Do What The Fuck You
" Want To Public License, Version 2, as published by Sam Hocevar.
" See http://sam.zoy.org/wtfpl/COPYING for more details.
"
"============================================================================
if exists('g:loaded_syntastic_php_phpstan_checker')
finish
endif
let g:loaded_syntastic_php_phpstan_checker = 1
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_php_phpstan_IsAvailable() dict
if !executable(self.getExec())
return 0
endif
return syntastic#util#versionIsAtLeast(self.getVersion(), [0, 7])
endfunction
function! SyntaxCheckers_php_phpstan_GetLocList() dict
let makeprg = self.makeprgBuild({
\ 'exe_after': 'analyse',
\ 'args': '--level=5',
\ 'args_after': '--errorFormat raw' })
let errorformat = '%f:%l:%m'
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'subtype' : 'Style' })
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'php',
\ 'name': 'phpstan'})
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set sw=4 sts=4 et fdm=marker:

View file

@ -0,0 +1 @@
/doc/tags

View file

@ -0,0 +1 @@
See the [contribution guidelines for pathogen.vim](https://github.com/tpope/vim-pathogen/blob/master/CONTRIBUTING.markdown).

View file

@ -0,0 +1,150 @@
# abolish.vim
I sat on this plugin for 3 years before releasing it, primarily
because it's so gosh darn hard to explain. It's three superficially
unrelated plugins in one that share a common theme: working with
variants of a word.
## Abbreviation
I know how to spell "separate". I know how to spell "desperate". My
fingers, however, have trouble distinguishing between the two, and I
invariably have a 50 percent chance of typing "seperate" or "desparate"
each time one of these comes up. At first, I tried abbreviations:
:iabbrev seperate separate
:iabbrev desparate desperate
But this falls short at the beginning of a sentence.
:iabbrev Seperate Separate
:iabbrev Desparate Desperate
To be really thorough, we need uppercase too!
:iabbrev SEPERATE SEPARATE
:iabbrev DESPARATE DESPERATE
Oh, but consider the noun form, and the adverb form!
:iabbrev seperation separation
:iabbrev desparation desperation
:iabbrev seperately separately
:iabbrev desparately desperately
:iabbrev Seperation separation
:iabbrev Desparation Desperation
:iabbrev Seperately Separately
:iabbrev Desparately Desperately
:iabbrev SEPERATION SEPARATION
:iabbrev DESPARATION DESPERATION
:iabbrev SEPERATELY SEPARATELY
:iabbrev DESPARATELY DESPERATELY
Wait, there's also "separates", "separated", "separating",
"separations", "separator"...
Abolish.vim provides a simpler way. The following one command produces
48 abbreviations including all of the above.
:Abolish {despa,sepe}rat{e,es,ed,ing,ely,ion,ions,or} {despe,sepa}rat{}
My current configuration has 25 Abolish commands that create hundreds of
corrections my fingers refuse to learn.
## Substitution
One time I had an application with a domain model called
"facility" that needed to be renamed to "building". So, a simple
search and replace, right?
:%s/facility/building/g
Oh, but the case variants!
:%s/Facility/Building/g
:%s/FACILITY/BUILDING/g
Wait, the plural is more than "s" so we need to get that too!
:%s/facilities/buildings/g
:%s/Facilities/Buildings/g
:%s/FACILITIES/BUILDINGS/g
Abolish.vim has your back. One command to do all six, and you can
repeat it with `&` too!
:%Subvert/facilit{y,ies}/building{,s}/g
From a conceptual level, one way to think about how this substitution
works is to imagine that in the braces you are declaring the
requirements for turning that word from singular to plural. In
the facility example, the same base letters in both the singular
and plural form of the word are `facilit` To turn "facility" to a
plural word you must change the `y` to `ies` so you specify
`{y,ies}` in the braces.
To convert the word "building" from singular to plural, again
look at the common letters between the singular and plural forms:
`building`. In this case you do not need to remove any letter
from building to turn it into plural form and you need to
add an `s` so the braces should be `{,s}`.
A few more examples:
Address to Reference
:Subvert/address{,es}/reference{,s}/g
Blog to Post (you can just do this with a regular :s also)
:Subvert/blog{,s}/post{,s}/g
Child to Adult
:Subvert/child{,ren}/adult{,s}/g
Be amazed as it correctly turns the word children into the word adults!
Die to Spinner
:Subvert/di{e,ce}/spinner{,s}/g
You can abbreviate it as `:S`, and it accepts the full range of flags
including things like `c` (confirm).
There's also a variant for searching and a variant for grepping.
## Coercion
Want to turn `fooBar` into `foo_bar`? Press `crs` (coerce to
snake\_case). MixedCase (`crm`), camelCase (`crc`), snake\_case
(`crs`), UPPER\_CASE (`cru`), dash-case (`cr-`), dot.case (`cr.`),
space case (`cr<space>`), and Title Case (`crt`) are all just 3
keystrokes away. These commands support
[repeat.vim](https://github.com/tpope/vim-repeat).
## Installation
If you don't have a preferred installation method, I recommend
installing [pathogen.vim](https://github.com/tpope/vim-pathogen), and
then simply copy and paste:
cd ~/.vim/bundle
git clone git://github.com/tpope/vim-abolish.git
Once help tags have been generated, you can view the manual with
`:help abolish`.
## Self-Promotion
Like abolish.vim? Follow the repository on
[GitHub](https://github.com/tpope/vim-abolish) and vote for it on
[vim.org](http://www.vim.org/scripts/script.php?script_id=1545). And if
you're feeling especially charitable, follow [tpope](http://tpo.pe/) on
[Twitter](http://twitter.com/tpope) and
[GitHub](https://github.com/tpope).
## License
Copyright (c) Tim Pope. Distributed under the same terms as Vim itself.
See `:help license`.

View file

@ -0,0 +1,181 @@
*abolish.txt* Language friendly searches, substitutions, and abbreviations
Author: Tim Pope <http://tpo.pe/>
License: Same terms as Vim itself (see |license|)
This plugin is only available if 'compatible' is not set.
INTRODUCTION *abolish* *:Abolish* *:Subvert*
Abolish lets you quickly find, substitute, and abbreviate several variations
of a word at once. By default, three case variants (foo, Foo, and FOO) are
operated on by every command.
Two commands are provided. :Abolish is the most general interface.
:Subvert provides an alternative, more concise syntax for searching and
substituting.
>
:Abolish [options] {abbreviation} {replacement}
:Abolish -delete [options] {abbreviation}
:Abolish -search [options] {pattern}
:Subvert/{pattern}[/flags]
:Abolish!-search [options] {pattern}
:Subvert?{pattern}[?flags]
:Abolish -search [options] {pattern} {grep-arguments}
:Subvert /{pattern}/[flags] {grep-options}
:Abolish!-search [options] {pattern} {grep-arguments}
:Subvert!/{pattern}/[flags] {grep-options}
:[range]Abolish -substitute [options] {pattern} {replacement}
:[range]Subvert/{pattern}/{replacement}[/flags]
<
*:S*
In addition to the :Subvert command, a :S synonym is provided if not
already defined. This will be used in examples below.
PATTERNS *abolish-patterns*
Patterns can include brace pairs that contain comma separated alternatives:
box{,es} => box, boxes, Box, Boxes, BOX, BOXES
For commands with a replacement, corresponding brace pairs are used in both
halves. If the replacement should be identical to the pattern, an empty
brace pair may be used. If fewer replacements are given than were given in
the pattern, they are looped. That is, {a,b} on the replacement side is the
same as {a,b,a,b,a,b,...} repeated indefinitely.
The following replaces several different misspellings of "necessary":
>
:%S/{,un}nec{ce,ces,e}sar{y,ily}/{}nec{es}sar{}/g
<
ABBREVIATING *abolish-abbrev*
By default :Abolish creates abbreviations, which replace words automatically
as you type. This is good for words you frequently misspell, or as
shortcuts for longer words. Since these are just Vim abbreviations, only
whole words will match.
>
:Abolish anomol{y,ies} anomal{}
:Abolish {,in}consistant{,ly} {}consistent{}
:Abolish Tqbf The quick, brown fox jumps over the lazy dog
<
Accepts the following options:
-buffer: buffer local
-cmdline: work in command line in addition to insert mode
A good place to define abbreviations is "after/plugin/abolish.vim",
relative to ~\vimfiles on Windows and ~/.vim everywhere else.
With a bang (:Abolish!) the abbreviation is also appended to the file in
g:abolish_save_file. The default is "after/plugin/abolish.vim", relative
to the install directory.
Abbreviations can be removed with :Abolish -delete:
>
Abolish -delete -buffer -cmdline anomol{y,ies}
<
SEARCHING *abolish-search*
The -search command does a search in a manner similar to / key.
search. After searching, you can use |n| and |N| as you would with a normal
search.
The following will search for box, Box, and BOX:
>
:Abolish -search box
<
When given a single word to operate on, :Subvert defaults to doing a
search as well:
>
:S/box/
<
This one searches for box, boxes, boxed, boxing, Box, Boxes, Boxed, Boxing,
BOX, BOXES, BOXED, and BOXING:
>
:S/box{,es,ed,ing}/
<
The following syntaxes search in reverse.
>
:Abolish! -search box
:S?box?
<
Flags can be given with the -flags= option to :Abolish, or by appending them
after the separator to :Subvert. The flags trigger the following behaviors:
I: Disable case variations (box, Box, BOX)
v: Match inside variable names (match my_box, myBox, but not mybox)
w: Match whole words (like surrounding with \< and \>)
A |search-offset| may follow the flags.
>
:Abolish -search -flags=avs+1 box
:S?box{,es,ed,ing}?we
<
GREPPING *abolish-grep*
Grepping works similar to searching, and is invoked when additional options
are given. These options are passed directly to the :grep command.
>
:Abolish -search box{,es}
:S /box{,es}/ *
:S /box/aw *.txt *.html
<
The slash delimiters must both be present if used with :Subvert. They may
both be omitted if no flags are used.
Both an external grepprg and vimgrep (via grepprg=internal) are supported.
With an external grep, the "v" flag behaves less intelligently, due to the
lack of look ahead and look behind support in grep regexps.
SUBSTITUTING *abolish-substitute*
Giving a range switches :Subvert into substitute mode. This command will
change box -> bag, boxes -> bags, Box -> Bag, Boxes -> Bags, BOX -> BAG,
BOXES -> BAGS across the entire document:
>
:%Abolish -substitute -flags=g box{,es} bag{,s}
:%S/box{,es}/bag{,s}/g
<
The "c", "e", "g", and "n" flags can be used from the substitute command
|:s_flags|, along with the "a", "I", "v", and "w" flags from searching.
COERCION *abolish-coercion* *cr*
Abolish's case mutating algorithms can be applied to the word under the cursor
using the cr mapping (mnemonic: CoeRce) followed by one of the following
characters:
c: camelCase
m: MixedCase
_: snake_case
s: snake_case
u: SNAKE_UPPERCASE
U: SNAKE_UPPERCASE
-: dash-case (not usually reversible; see |abolish-coercion-reversible|)
k: kebab-case (not usually reversible; see |abolish-coercion-reversible|)
.: dot.case (not usually reversible; see |abolish-coercion-reversible|)
<space>: space case (not usually reversible; see |abolish-coercion-reversible|)
t: Title Case (not usually reversible; see |abolish-coercion-reversible|)
For example, cru on a lowercase word is a slightly easier to type equivalent
to gUiw.
COERCION REVERSIBILITY *abolish-coercion-reversible*
Some separators, such as "-" and ".", are listed as "not usually reversible".
The reason is that these are not "keyword characters", so vim (and
abolish.vim) will treat them as breaking a word.
For example: "key_word" is a single keyword. The dash-case version,
"key-word", is treated as two keywords, "key" and "word".
This behaviour is governed by the 'iskeyword' option. If a separator appears
in 'iskeyword', the corresponding coercion will be reversible. For instance,
dash-case is reversible in 'lisp' files, and dot-case is reversible in R
files.
vim:tw=78:ts=8:ft=help:norl:

View file

@ -0,0 +1,631 @@
" abolish.vim - Language friendly searches, substitutions, and abbreviations
" Maintainer: Tim Pope <http://tpo.pe/>
" Version: 1.1
" GetLatestVimScripts: 1545 1 :AutoInstall: abolish.vim
" Initialization {{{1
if exists("g:loaded_abolish") || &cp || v:version < 700
finish
endif
let g:loaded_abolish = 1
if !exists("g:abolish_save_file")
if isdirectory(expand("~/.vim"))
let g:abolish_save_file = expand("~/.vim/after/plugin/abolish.vim")
elseif isdirectory(expand("~/vimfiles")) || has("win32")
let g:abolish_save_file = expand("~/vimfiles/after/plugin/abolish.vim")
else
let g:abolish_save_file = expand("~/.vim/after/plugin/abolish.vim")
endif
endif
" }}}1
" Utility functions {{{1
function! s:function(name)
return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),''))
endfunction
function! s:send(self,func,...)
if type(a:func) == type('') || type(a:func) == type(0)
let Func = get(a:self,a:func,'')
else
let Func = a:func
endif
let s = type(a:self) == type({}) ? a:self : {}
if type(Func) == type(function('tr'))
return call(Func,a:000,s)
elseif type(Func) == type({}) && has_key(Func,'apply')
return call(Func.apply,a:000,Func)
elseif type(Func) == type({}) && has_key(Func,'call')
return call(Func.call,a:000,s)
elseif type(Func) == type('') && Func == '' && has_key(s,'function missing')
return call('s:send',[s,'function missing',a:func] + a:000)
else
return Func
endif
endfunction
let s:object = {}
function! s:object.clone(...)
let sub = deepcopy(self)
return a:0 ? extend(sub,a:1) : sub
endfunction
if !exists("g:Abolish")
let Abolish = {}
endif
call extend(Abolish, s:object, 'force')
call extend(Abolish, {'Coercions': {}}, 'keep')
function! s:throw(msg)
let v:errmsg = a:msg
throw "Abolish: ".a:msg
endfunction
function! s:words()
let words = []
let lnum = line('w0')
while lnum <= line('w$')
let line = getline(lnum)
let col = 0
while match(line,'\<\k\k\+\>',col) != -1
let words += [matchstr(line,'\<\k\k\+\>',col)]
let col = matchend(line,'\<\k\k\+\>',col)
endwhile
let lnum += 1
endwhile
return words
endfunction
function! s:extractopts(list,opts)
let i = 0
while i < len(a:list)
if a:list[i] =~ '^-[^=]' && has_key(a:opts,matchstr(a:list[i],'-\zs[^=]*'))
let key = matchstr(a:list[i],'-\zs[^=]*')
let value = matchstr(a:list[i],'=\zs.*')
if type(get(a:opts,key)) == type([])
let a:opts[key] += [value]
elseif type(get(a:opts,key)) == type(0)
let a:opts[key] = 1
else
let a:opts[key] = value
endif
else
let i += 1
continue
endif
call remove(a:list,i)
endwhile
return a:opts
endfunction
" }}}1
" Dictionary creation {{{1
function! s:mixedcase(word)
return substitute(s:camelcase(a:word),'^.','\u&','')
endfunction
function! s:camelcase(word)
let word = substitute(a:word, '-', '_', 'g')
if word !~# '_' && word =~# '\l'
return substitute(word,'^.','\l&','')
else
return substitute(word,'\C\(_\)\=\(.\)','\=submatch(1)==""?tolower(submatch(2)) : toupper(submatch(2))','g')
endif
endfunction
function! s:snakecase(word)
let word = substitute(a:word,'::','/','g')
let word = substitute(word,'\(\u\+\)\(\u\l\)','\1_\2','g')
let word = substitute(word,'\(\l\|\d\)\(\u\)','\1_\2','g')
let word = substitute(word,'[.-]','_','g')
let word = tolower(word)
return word
endfunction
function! s:uppercase(word)
return toupper(s:snakecase(a:word))
endfunction
function! s:dashcase(word)
return substitute(s:snakecase(a:word),'_','-','g')
endfunction
function! s:spacecase(word)
return substitute(s:snakecase(a:word),'_',' ','g')
endfunction
function! s:dotcase(word)
return substitute(s:snakecase(a:word),'_','.','g')
endfunction
function! s:titlecase(word)
return substitute(s:spacecase(a:word), '\(\<\w\)','\=toupper(submatch(1))','g')
endfunction
call extend(Abolish, {
\ 'camelcase': s:function('s:camelcase'),
\ 'mixedcase': s:function('s:mixedcase'),
\ 'snakecase': s:function('s:snakecase'),
\ 'uppercase': s:function('s:uppercase'),
\ 'dashcase': s:function('s:dashcase'),
\ 'dotcase': s:function('s:dotcase'),
\ 'spacecase': s:function('s:spacecase'),
\ 'titlecase': s:function('s:titlecase')
\ }, 'keep')
function! s:create_dictionary(lhs,rhs,opts)
let dictionary = {}
let i = 0
let expanded = s:expand_braces({a:lhs : a:rhs})
for [lhs,rhs] in items(expanded)
if get(a:opts,'case',1)
let dictionary[s:mixedcase(lhs)] = s:mixedcase(rhs)
let dictionary[tolower(lhs)] = tolower(rhs)
let dictionary[toupper(lhs)] = toupper(rhs)
endif
let dictionary[lhs] = rhs
endfor
let i += 1
return dictionary
endfunction
function! s:expand_braces(dict)
let new_dict = {}
for [key,val] in items(a:dict)
if key =~ '{.*}'
let redo = 1
let [all,kbefore,kmiddle,kafter;crap] = matchlist(key,'\(.\{-\}\){\(.\{-\}\)}\(.*\)')
let [all,vbefore,vmiddle,vafter;crap] = matchlist(val,'\(.\{-\}\){\(.\{-\}\)}\(.*\)') + ["","","",""]
if all == ""
let [vbefore,vmiddle,vafter] = [val, ",", ""]
endif
let targets = split(kmiddle,',',1)
let replacements = split(vmiddle,',',1)
if replacements == [""]
let replacements = targets
endif
for i in range(0,len(targets)-1)
let new_dict[kbefore.targets[i].kafter] = vbefore.replacements[i%len(replacements)].vafter
endfor
else
let new_dict[key] = val
endif
endfor
if exists("redo")
return s:expand_braces(new_dict)
else
return new_dict
endif
endfunction
" }}}1
" Abolish Dispatcher {{{1
function! s:SubComplete(A,L,P)
if a:A =~ '^[/?]\k\+$'
let char = strpart(a:A,0,1)
return join(map(s:words(),'char . v:val'),"\n")
elseif a:A =~# '^\k\+$'
return join(s:words(),"\n")
endif
endfunction
function! s:Complete(A,L,P)
let g:L = a:L
" Vim bug: :Abolish -<Tab> calls this function with a:A equal to 0
if a:A =~# '^[^/?-]' && type(a:A) != type(0)
return join(s:words(),"\n")
elseif a:L =~# '^\w\+\s\+\%(-\w*\)\=$'
return "-search\n-substitute\n-delete\n-buffer\n-cmdline\n"
elseif a:L =~# ' -\%(search\|substitute\)\>'
return "-flags="
else
return "-buffer\n-cmdline"
endif
endfunction
let s:commands = {}
let s:commands.abstract = s:object.clone()
function! s:commands.abstract.dispatch(bang,line1,line2,count,args)
return self.clone().go(a:bang,a:line1,a:line2,a:count,a:args)
endfunction
function! s:commands.abstract.go(bang,line1,line2,count,args)
let self.bang = a:bang
let self.line1 = a:line1
let self.line2 = a:line2
let self.count = a:count
return self.process(a:bang,a:line1,a:line2,a:count,a:args)
endfunction
function! s:dispatcher(bang,line1,line2,count,args)
let i = 0
let args = copy(a:args)
let command = s:commands.abbrev
while i < len(args)
if args[i] =~# '^-\w\+$' && has_key(s:commands,matchstr(args[i],'-\zs.*'))
let command = s:commands[matchstr(args[i],'-\zs.*')]
call remove(args,i)
break
endif
let i += 1
endwhile
try
return command.dispatch(a:bang,a:line1,a:line2,a:count,args)
catch /^Abolish: /
echohl ErrorMsg
echo v:errmsg
echohl NONE
return ""
endtry
endfunction
" }}}1
" Subvert Dispatcher {{{1
function! s:subvert_dispatcher(bang,line1,line2,count,args)
try
return s:parse_subvert(a:bang,a:line1,a:line2,a:count,a:args)
catch /^Subvert: /
echohl ErrorMsg
echo v:errmsg
echohl NONE
return ""
endtry
endfunction
function! s:parse_subvert(bang,line1,line2,count,args)
if a:args =~ '^\%(\w\|$\)'
let args = (a:bang ? "!" : "").a:args
else
let args = a:args
endif
let separator = matchstr(args,'^.')
let split = split(args,separator,1)[1:]
if a:count || split == [""]
return s:parse_substitute(a:bang,a:line1,a:line2,a:count,split)
elseif len(split) == 1
return s:find_command(separator,"",split[0])
elseif len(split) == 2 && split[1] =~# '^[A-Za-z]*n[A-Za-z]*$'
return s:parse_substitute(a:bang,a:line1,a:line2,a:count,[split[0],"",split[1]])
elseif len(split) == 2 && split[1] =~# '^[A-Za-z]*\%([+-]\d\+\)\=$'
return s:find_command(separator,split[1],split[0])
elseif len(split) >= 2 && split[1] =~# '^[A-Za-z]* '
let flags = matchstr(split[1],'^[A-Za-z]*')
let rest = matchstr(join(split[1:],separator),' \zs.*')
return s:grep_command(rest,a:bang,flags,split[0])
elseif len(split) >= 2 && separator == ' '
return s:grep_command(join(split[1:],' '),a:bang,"",split[0])
else
return s:parse_substitute(a:bang,a:line1,a:line2,a:count,split)
endif
endfunction
function! s:normalize_options(flags)
if type(a:flags) == type({})
let opts = a:flags
let flags = get(a:flags,"flags","")
else
let opts = {}
let flags = a:flags
endif
let g:op1 = copy(opts)
if flags =~# 'w'
let opts.boundaries = 2
elseif flags =~# 'v'
let opts.boundaries = 1
elseif !has_key(opts,'boundaries')
let opts.boundaries = 0
endif
let opts.case = (flags !~# 'I' ? get(opts,'case',1) : 0)
let opts.flags = substitute(flags,'\C[avIiw]','','g')
let g:op2 = copy(opts)
return opts
endfunction
" }}}1
" Searching {{{1
function! s:subesc(pattern)
return substitute(a:pattern,'[][\\/.*+?~%()&]','\\&','g')
endfunction
function! s:sort(a,b)
if a:a ==? a:b
return a:a == a:b ? 0 : a:a > a:b ? 1 : -1
elseif strlen(a:a) == strlen(a:b)
return a:a >? a:b ? 1 : -1
else
return strlen(a:a) < strlen(a:b) ? 1 : -1
endif
endfunction
function! s:pattern(dict,boundaries)
if a:boundaries == 2
let a = '<'
let b = '>'
elseif a:boundaries
let a = '%(<|_@<=|[[:lower:]]@<=[[:upper:]]@=)'
let b = '%(>|_@=|[[:lower:]]@<=[[:upper:]]@=)'
else
let a = ''
let b = ''
endif
return '\v\C'.a.'%('.join(map(sort(keys(a:dict),function('s:sort')),'s:subesc(v:val)'),'|').')'.b
endfunction
function! s:egrep_pattern(dict,boundaries)
if a:boundaries == 2
let a = '\<'
let b = '\>'
elseif a:boundaries
let a = '(\<\|_)'
let b = '(\>\|_\|[[:upper:]][[:lower:]])'
else
let a = ''
let b = ''
endif
return a.'('.join(map(sort(keys(a:dict),function('s:sort')),'s:subesc(v:val)'),'\|').')'.b
endfunction
function! s:c()
call histdel('search',-1)
return ""
endfunction
function! s:find_command(cmd,flags,word)
let opts = s:normalize_options(a:flags)
let dict = s:create_dictionary(a:word,"",opts)
" This is tricky. If we use :/pattern, the search drops us at the
" beginning of the line, and we can't use position flags (e.g., /foo/e).
" If we use :norm /pattern, we leave ourselves vulnerable to "press enter"
" prompts (even with :silent).
let cmd = (a:cmd =~ '[?!]' ? '?' : '/')
let @/ = s:pattern(dict,opts.boundaries)
if opts.flags == "" || !search(@/,'n')
return "norm! ".cmd."\<CR>"
elseif opts.flags =~ ';[/?]\@!'
call s:throw("E386: Expected '?' or '/' after ';'")
else
return "exe 'norm! ".cmd.cmd.opts.flags."\<CR>'|call histdel('search',-1)"
return ""
endif
endfunction
function! s:grep_command(args,bang,flags,word)
let opts = s:normalize_options(a:flags)
let dict = s:create_dictionary(a:word,"",opts)
if &grepprg == "internal"
let lhs = "'".s:pattern(dict,opts.boundaries)."'"
else
let lhs = "-E '".s:egrep_pattern(dict,opts.boundaries)."'"
endif
return "grep".(a:bang ? "!" : "")." ".lhs." ".a:args
endfunction
let s:commands.search = s:commands.abstract.clone()
let s:commands.search.options = {"word": 0, "variable": 0, "flags": ""}
function! s:commands.search.process(bang,line1,line2,count,args)
call s:extractopts(a:args,self.options)
if self.options.word
let self.options.flags .= "w"
elseif self.options.variable
let self.options.flags .= "v"
endif
let opts = s:normalize_options(self.options)
if len(a:args) > 1
return s:grep_command(join(a:args[1:]," "),a:bang,opts,a:args[0])
elseif len(a:args) == 1
return s:find_command(a:bang ? "!" : " ",opts,a:args[0])
else
call s:throw("E471: Argument required")
endif
endfunction
" }}}1
" Substitution {{{1
function! Abolished()
return get(g:abolish_last_dict,submatch(0),submatch(0))
endfunction
function! s:substitute_command(cmd,bad,good,flags)
let opts = s:normalize_options(a:flags)
let dict = s:create_dictionary(a:bad,a:good,opts)
let lhs = s:pattern(dict,opts.boundaries)
let g:abolish_last_dict = dict
return a:cmd.'/'.lhs.'/\=Abolished()'."/".opts.flags
endfunction
function! s:parse_substitute(bang,line1,line2,count,args)
if get(a:args,0,'') =~ '^[/?'']'
let separator = matchstr(a:args[0],'^.')
let args = split(join(a:args,' '),separator,1)
call remove(args,0)
else
let args = a:args
endif
if len(args) < 2
call s:throw("E471: Argument required")
elseif len(args) > 3
call s:throw("E488: Trailing characters")
endif
let [bad,good,flags] = (args + [""])[0:2]
if a:count == 0
let cmd = "substitute"
else
let cmd = a:line1.",".a:line2."substitute"
endif
return s:substitute_command(cmd,bad,good,flags)
endfunction
let s:commands.substitute = s:commands.abstract.clone()
let s:commands.substitute.options = {"word": 0, "variable": 0, "flags": "g"}
function! s:commands.substitute.process(bang,line1,line2,count,args)
call s:extractopts(a:args,self.options)
if self.options.word
let self.options.flags .= "w"
elseif self.options.variable
let self.options.flags .= "v"
endif
let opts = s:normalize_options(self.options)
if len(a:args) <= 1
call s:throw("E471: Argument required")
else
let good = join(a:args[1:],"")
let cmd = a:bang ? "." : "%"
return s:substitute_command(cmd,a:args[0],good,self.options)
endif
endfunction
" }}}1
" Abbreviations {{{1
function! s:badgood(args)
let words = filter(copy(a:args),'v:val !~ "^-"')
call filter(a:args,'v:val =~ "^-"')
if empty(words)
call s:throw("E471: Argument required")
elseif !empty(a:args)
call s:throw("Unknown argument: ".a:args[0])
endif
let [bad; words] = words
return [bad, join(words," ")]
endfunction
function! s:abbreviate_from_dict(cmd,dict)
for [lhs,rhs] in items(a:dict)
exe a:cmd lhs rhs
endfor
endfunction
let s:commands.abbrev = s:commands.abstract.clone()
let s:commands.abbrev.options = {"buffer":0,"cmdline":0,"delete":0}
function! s:commands.abbrev.process(bang,line1,line2,count,args)
let args = copy(a:args)
call s:extractopts(a:args,self.options)
if self.options.delete
let cmd = "unabbrev"
let good = ""
else
let cmd = "noreabbrev"
endif
if !self.options.cmdline
let cmd = "i" . cmd
endif
if self.options.delete
let cmd = "silent! ".cmd
endif
if self.options.buffer
let cmd = cmd . " <buffer>"
endif
let [bad, good] = s:badgood(a:args)
if substitute(bad,'{.\{-\}.}','','g') !~ '^\k\+$'
call s:throw("E474: Invalid argument (not a keyword: ".string(bad).")")
endif
if !self.options.delete && good == ""
call s:throw("E471: Argument required".a:args[0])
endif
let dict = s:create_dictionary(bad,good,self.options)
call s:abbreviate_from_dict(cmd,dict)
if a:bang
let i = 0
let str = "Abolish ".join(args," ")
let file = g:abolish_save_file
if !isdirectory(fnamemodify(file,':h'))
call mkdir(fnamemodify(file,':h'),'p')
endif
if filereadable(file)
let old = readfile(file)
else
let old = ["\" Exit if :Abolish isn't available.","if !exists(':Abolish')"," finish","endif",""]
endif
call writefile(old + [str],file)
endif
return ""
endfunction
let s:commands.delete = s:commands.abbrev.clone()
let s:commands.delete.options.delete = 1
" }}}1
" Maps {{{1
function! s:unknown_coercion(letter,word)
return a:word
endfunction
call extend(Abolish.Coercions, {
\ 'c': Abolish.camelcase,
\ 'm': Abolish.mixedcase,
\ 's': Abolish.snakecase,
\ '_': Abolish.snakecase,
\ 'u': Abolish.uppercase,
\ 'U': Abolish.uppercase,
\ '-': Abolish.dashcase,
\ 'k': Abolish.dashcase,
\ '.': Abolish.dotcase,
\ ' ': Abolish.spacecase,
\ 't': Abolish.titlecase,
\ "function missing": s:function("s:unknown_coercion")
\}, "keep")
function! s:coerce(transformation)
let clipboard = &clipboard
try
set clipboard=
let regbody = getreg('"')
let regtype = getregtype('"')
let c = v:count1
while c > 0
let c -= 1
norm! yiw
let word = @@
let @@ = s:send(g:Abolish.Coercions,a:transformation,word)
if !exists('begin')
let begin = getpos("'[")
endif
if word !=# @@
let changed = 1
norm! viwpw
else
norm! w
endif
endwhile
call setreg('"',regbody,regtype)
call setpos("'[",begin)
call setpos(".",begin)
if exists("changed")
silent! call repeat#set("\<Plug>Coerce".a:transformation)
endif
finally
let &clipboard = clipboard
endtry
endfunction
nnoremap <silent> <Plug>Coerce :<C-U>call <SID>coerce(nr2char(getchar()))<CR>
" }}}1
if !exists("g:abolish_no_mappings") || ! g:abolish_no_mappings
nmap cr <Plug>Coerce
endif
command! -nargs=+ -bang -bar -range=0 -complete=custom,s:Complete Abolish
\ :exec s:dispatcher(<bang>0,<line1>,<line2>,<count>,[<f-args>])
command! -nargs=1 -bang -bar -range=0 -complete=custom,s:SubComplete Subvert
\ :exec s:subvert_dispatcher(<bang>0,<line1>,<line2>,<count>,<q-args>)
if exists(':S') != 2
command -nargs=1 -bang -bar -range=0 -complete=custom,s:SubComplete S
\ :exec s:subvert_dispatcher(<bang>0,<line1>,<line2>,<count>,<q-args>)
endif
" vim:set ft=vim sw=2 sts=2:

View file

@ -42,8 +42,6 @@
" 0.1 - 06 June 2009 " 0.1 - 06 June 2009
" - Initial public release of mako indent file " - Initial public release of mako indent file
let sw=2 " default shiftwidth of 2 spaces
if exists("b:did_indent") if exists("b:did_indent")
finish finish
endif endif
@ -53,6 +51,9 @@ setlocal nosmartindent
setlocal noautoindent setlocal noautoindent
setlocal nocindent setlocal nocindent
setlocal nolisp setlocal nolisp
setlocal expandtab
setlocal softtabstop=2
setlocal shiftwidth=2
setlocal indentexpr=GetMakoIndent() setlocal indentexpr=GetMakoIndent()
setlocal indentkeys+=*<Return>,<>>,<bs>,end,: setlocal indentkeys+=*<Return>,<>>,<bs>,end,:

View file

@ -298,6 +298,9 @@ endfunction
function! s:repo_tree(...) dict abort function! s:repo_tree(...) dict abort
if self.dir() =~# '/\.git$' if self.dir() =~# '/\.git$'
let dir = self.dir()[0:-6] let dir = self.dir()[0:-6]
if dir !~# '/'
let dir .= '/'
endif
else else
let dir = s:configured_tree(self.git_dir) let dir = s:configured_tree(self.git_dir)
endif endif
@ -972,11 +975,14 @@ function! s:StageToggle(lnum1,lnum2) abort
continue continue
endif endif
execute lnum execute lnum
if filename =~ ' -> ' if section ==# 'staged'
let cmd = ['mv','--'] + reverse(split(filename,' -> ')) if filename =~ ' -> '
let filename = cmd[-1] let files_to_unstage = split(filename,' -> ')
elseif section ==# 'staged' else
let cmd = ['reset','-q','--',filename] let files_to_unstage = [filename]
endif
let filename = files_to_unstage[-1]
let cmd = ['reset','-q','--'] + files_to_unstage
elseif getline(lnum) =~# '^#\tdeleted:' elseif getline(lnum) =~# '^#\tdeleted:'
let cmd = ['rm','--',filename] let cmd = ['rm','--',filename]
elseif getline(lnum) =~# '^#\tmodified:' elseif getline(lnum) =~# '^#\tmodified:'
@ -1118,7 +1124,7 @@ function! s:Commit(args, ...) abort
elseif error ==# '!' elseif error ==# '!'
return s:Status() return s:Status()
else else
call s:throw(error) call s:throw(empty(error)?join(errors, ' '):error)
endif endif
endif endif
catch /^fugitive:/ catch /^fugitive:/
@ -1385,6 +1391,7 @@ function! s:Edit(cmd,bang,...) abort
endif endif
endif endif
endfor endfor
diffoff!
endif endif
endif endif
endif endif
@ -2894,7 +2901,7 @@ function! s:cfile() abort
let ref = matchstr(getline('.'),'\x\{40\}') let ref = matchstr(getline('.'),'\x\{40\}')
echoerr "warning: unknown context ".matchstr(getline('.'),'^\l*') echoerr "warning: unknown context ".matchstr(getline('.'),'^\l*')
elseif getline('.') =~# '^[+-]\{3\} [abciwo12]\=/' elseif getline('.') =~# '^[+-]\{3\} [abciow12]\=/'
let ref = getline('.')[4:] let ref = getline('.')[4:]
elseif getline('.') =~# '^[+-]' && search('^@@ -\d\+,\d\+ +\d\+,','bnW') elseif getline('.') =~# '^[+-]' && search('^@@ -\d\+,\d\+ +\d\+,','bnW')
@ -2908,7 +2915,7 @@ function! s:cfile() abort
let lnum -= 1 let lnum -= 1
endwhile endwhile
let offset += matchstr(getline(lnum), type.'\zs\d\+') let offset += matchstr(getline(lnum), type.'\zs\d\+')
let ref = getline(search('^'.type.'\{3\} [abciwo12]/','bnW'))[4:-1] let ref = getline(search('^'.type.'\{3\} [abciow12]/','bnW'))[4:-1]
let dcmds = [offset, 'normal!zv'] let dcmds = [offset, 'normal!zv']
elseif getline('.') =~# '^rename from ' elseif getline('.') =~# '^rename from '
@ -2917,22 +2924,22 @@ function! s:cfile() abort
let ref = 'b/'.getline('.')[10:] let ref = 'b/'.getline('.')[10:]
elseif getline('.') =~# '^@@ -\d\+,\d\+ +\d\+,' elseif getline('.') =~# '^@@ -\d\+,\d\+ +\d\+,'
let diff = getline(search('^diff --git \%([abciwo12]/.*\|/dev/null\) \%([abciwo12]/.*\|/dev/null\)', 'bcnW')) let diff = getline(search('^diff --git \%([abciow12]/.*\|/dev/null\) \%([abciow12]/.*\|/dev/null\)', 'bcnW'))
let offset = matchstr(getline('.'), '+\zs\d\+') let offset = matchstr(getline('.'), '+\zs\d\+')
let dref = matchstr(diff, '\Cdiff --git \zs\%([abciwo12]/.*\|/dev/null\)\ze \%([abciwo12]/.*\|/dev/null\)') let dref = matchstr(diff, '\Cdiff --git \zs\%([abciow12]/.*\|/dev/null\)\ze \%([abciow12]/.*\|/dev/null\)')
let ref = matchstr(diff, '\Cdiff --git \%([abciwo12]/.*\|/dev/null\) \zs\%([abciwo12]/.*\|/dev/null\)') let ref = matchstr(diff, '\Cdiff --git \%([abciow12]/.*\|/dev/null\) \zs\%([abciow12]/.*\|/dev/null\)')
let dcmd = 'Gdiff! +'.offset let dcmd = 'Gdiff! +'.offset
elseif getline('.') =~# '^diff --git \%([abciwo12]/.*\|/dev/null\) \%([abciwo12]/.*\|/dev/null\)' elseif getline('.') =~# '^diff --git \%([abciow12]/.*\|/dev/null\) \%([abciow12]/.*\|/dev/null\)'
let dref = matchstr(getline('.'),'\Cdiff --git \zs\%([abciwo12]/.*\|/dev/null\)\ze \%([abciwo12]/.*\|/dev/null\)') let dref = matchstr(getline('.'),'\Cdiff --git \zs\%([abciow12]/.*\|/dev/null\)\ze \%([abciow12]/.*\|/dev/null\)')
let ref = matchstr(getline('.'),'\Cdiff --git \%([abciwo12]/.*\|/dev/null\) \zs\%([abciwo12]/.*\|/dev/null\)') let ref = matchstr(getline('.'),'\Cdiff --git \%([abciow12]/.*\|/dev/null\) \zs\%([abciow12]/.*\|/dev/null\)')
let dcmd = 'Gdiff!' let dcmd = 'Gdiff!'
elseif getline('.') =~# '^index ' && getline(line('.')-1) =~# '^diff --git \%([abciwo12]/.*\|/dev/null\) \%([abciwo12]/.*\|/dev/null\)' elseif getline('.') =~# '^index ' && getline(line('.')-1) =~# '^diff --git \%([abciow12]/.*\|/dev/null\) \%([abciow12]/.*\|/dev/null\)'
let line = getline(line('.')-1) let line = getline(line('.')-1)
let dref = matchstr(line,'\Cdiff --git \zs\%([abciwo12]/.*\|/dev/null\)\ze \%([abciwo12]/.*\|/dev/null\)') let dref = matchstr(line,'\Cdiff --git \zs\%([abciow12]/.*\|/dev/null\)\ze \%([abciow12]/.*\|/dev/null\)')
let ref = matchstr(line,'\Cdiff --git \%([abciwo12]/.*\|/dev/null\) \zs\%([abciwo12]/.*\|/dev/null\)') let ref = matchstr(line,'\Cdiff --git \%([abciow12]/.*\|/dev/null\) \zs\%([abciow12]/.*\|/dev/null\)')
let dcmd = 'Gdiff!' let dcmd = 'Gdiff!'
elseif line('$') == 1 && getline('.') =~ '^\x\{40\}$' elseif line('$') == 1 && getline('.') =~ '^\x\{40\}$'
@ -2957,9 +2964,9 @@ function! s:cfile() abort
let prefixes.a = myhash.'^:' let prefixes.a = myhash.'^:'
let prefixes.b = myhash.':' let prefixes.b = myhash.':'
endif endif
let ref = s:sub(ref, '^\(\w\)/', 'get(prefixes, submatch(1), "HEAD:")') let ref = substitute(ref, '^\(\w\)/', '\=get(prefixes, submatch(1), "HEAD:")', '')
if exists('dref') if exists('dref')
let dref = s:sub(dref, '^\(\w\)/', 'get(prefixes, submatch(1), "HEAD:")') let dref = substitute(dref, '^\(\w\)/', '\=get(prefixes, submatch(1), "HEAD:")', '')
endif endif
if ref ==# '/dev/null' if ref ==# '/dev/null'

View file

@ -1,9 +1,9 @@
Thanks for improving vim-go! Before you dive in please read the following: Thanks for improving vim-go! Before you dive in please read the following:
1. Please read our 1. Please read our
[FAQ](https://github.com/fatih/vim-go/wiki/FAQ-Troubleshooting), it might [Documentation](https://github.com/fatih/vim-go/blob/master/doc/vim-go.txt), it might
have answers for your problem have answers for your problem
2. If you add a new feature please don't forget to update the documentation: 2. If you add a new feature please don't forget to update the documentation:
[doc/vim-go.txt](https://github.com/fatih/vim-go/blob/master/doc/vim-go.txt) [doc/vim-go.txt](https://github.com/fatih/vim-go/blob/master/doc/vim-go.txt.
3. If it's a breaking change or exceed +100 lines please open an issue first 3. If it's a breaking change or exceed +100 lines please open an issue first
and describe the changes you want to make. and describe the changes you want to make.

View file

@ -1,12 +1,27 @@
## unplanned ## unplanned
FEATURES:
* New `:GoKeyify` command that turns unkeyed struct literals into keyed struct literals. [gh-1258]
* New `g:go_addtags_transform` setting to change the transform rule (snakecase, camelcase, etc..) for `:GoAddTags` command [gh-1275]
* New snippet shortcut assigned to `ife` that expands to `if err := foo(); err != nil { ... }` [gh-1268]
IMPROVEMENTS IMPROVEMENTS
* :GoMetaLinter can now exclude linters with the new `g:go_metalinter_excludes` option [gh-1253] * :GoMetaLinter can now exclude linters with the new `g:go_metalinter_excludes` option [gh-1253]
* Override `<C-LeftMouse>` mapping so `:GoDef` is used by default (as we do the same for `CTRL-]`, `gd`, etc. [gh-1264]
BUG FIXES: BUG FIXES:
* job: fix race between channel close and job exit [gh-1247] * job: fix race between channel close and job exit [gh-1247]
* internal: fix system calls when using tcsh [gh-1276]
* path: return the unmodified GOPATH if autodetect is disabled [gh-1280]
* fix jumping to quickfix window when autom gometalinter on save was enabled [gh-1293]
BACKWARDS INCOMPATIBILITIES:
* `:GoLint` works on the whole directory instead of the current file. To use it for the current file give it as an argument, i.e `:GoLint foo.go` [gh-1295]
* `go_snippet_case_type` is removed in favor of the new `go_addtags_transform` setting [gh-1299]
## 1.12 - (March 29, 2017) ## 1.12 - (March 29, 2017)

View file

@ -0,0 +1,58 @@
function! go#keyify#Keyify()
let old_gopath = $GOPATH
let $GOPATH = go#path#Detect()
let bin_path = go#path#CheckBinPath("keyify")
let fname = fnamemodify(expand("%"), ':p:gs?\\?/?')
if empty(bin_path) || !exists('*json_decode')
let $GOPATH = old_gopath
return
endif
" Get result of command as json, that contains `start`, `end` and `replacement`
let command = printf("%s -json %s:#%s", bin_path, fname, go#util#OffsetCursor())
let output = go#util#System(command)
silent! let result = json_decode(output)
" We want to output the error message in case the result isn't a JSON
if type(result) != type({})
call go#util#EchoError(s:chomp(output))
let $GOPATH = old_gopath
return
endif
" Because keyify returns the byte before the region we want, we goto the
" byte after that
execute "goto" result.start + 1
let start = getpos('.')
execute "goto" result.end
let end = getpos('.')
let vis_start = getpos("'<")
let vis_end = getpos("'>")
" Replace contents between start and end with `replacement`
call setpos("'<", start)
call setpos("'>", end)
let select = 'gv'
" Make sure the visual mode is 'v', to avoid some bugs
normal! gv
if mode() !=# 'v'
let select .= 'v'
endif
silent! execute "normal!" select."\"=result.replacement\<cr>p"
" Replacement text isn't aligned, so it needs fix
normal! '<v'>=
call setpos("'<", vis_start)
call setpos("'>", vis_end)
let $GOPATH = old_gopath
endfunction
function! s:chomp(string)
return substitute(a:string, '\n\+$', '', '')
endfunction

View file

@ -123,12 +123,11 @@ function! go#lint#Golint(...) abort
endif endif
if a:0 == 0 if a:0 == 0
let goargs = shellescape(expand('%')) let out = go#util#System(bin_path)
else else
let goargs = go#util#Shelljoin(a:000) let out = go#util#System(bin_path . " " . go#util#Shelljoin(a:000))
endif endif
let out = go#util#System(bin_path . " " . goargs)
if empty(out) if empty(out)
echon "vim-go: " | echohl Function | echon "[lint] PASS" | echohl None echon "vim-go: " | echohl Function | echon "[lint] PASS" | echohl None
return return
@ -255,9 +254,13 @@ function s:lint_job(args)
caddexpr a:msg caddexpr a:msg
let &errorformat = old_errorformat let &errorformat = old_errorformat
" TODO(arslan): cursor still jumps to first error even If I don't want " TODO(jinleileiking): give a configure to jump or not
" it. Seems like there is a regression somewhere, but not sure where. let l:winnr = winnr()
copen copen
exe l:winnr . "wincmd w"
endfunction endfunction
function! s:exit_cb(job, exitval) closure function! s:exit_cb(job, exitval) closure

View file

@ -33,22 +33,16 @@ function! go#path#GoPath(...) abort
let $GOPATH = a:1 let $GOPATH = a:1
endfunction endfunction
" Default returns the default GOPATH. If there is a single GOPATH it returns " Default returns the default GOPATH. If GOPATH is not set, it uses the
" it. For multiple GOPATHS separated with a the OS specific separator, only " default GOPATH set starting with Go 1.8. This GOPATH can be retrieved via
" the first one is returned. If GOPATH is not set, it uses the default GOPATH " 'go env GOPATH'
" set starting with GO 1.8. This GOPATH can be retrieved via 'go env GOPATH'
function! go#path#Default() abort function! go#path#Default() abort
if $GOPATH == "" if $GOPATH == ""
" use default GOPATH via go env " use default GOPATH via go env
return go#util#gopath() return go#util#gopath()
endif endif
let go_paths = split($GOPATH, go#util#PathListSep()) return $GOPATH
if len(go_paths) == 1
return $GOPATH
endif
return go_paths[0]
endfunction endfunction
" HasPath checks whether the given path exists in GOPATH environment variable " HasPath checks whether the given path exists in GOPATH environment variable
@ -134,8 +128,8 @@ function! go#path#BinPath() abort
elseif $GOBIN != "" elseif $GOBIN != ""
let bin_path = $GOBIN let bin_path = $GOBIN
else else
" GOPATH (user set or default GO) let go_paths = split(go#path#Default(), go#util#PathListSep())
let bin_path = expand(go#path#Default() . "/bin/") let bin_path = expand(go_paths[0] . "/bin/")
endif endif
return bin_path return bin_path

View file

@ -122,11 +122,13 @@ func s:create_cmd(args) abort
let l:offset = a:args.offset let l:offset = a:args.offset
let l:mode = a:args.mode let l:mode = a:args.mode
let l:cmd_args = a:args.cmd_args let l:cmd_args = a:args.cmd_args
let l:modifytags_transform = get(g:, 'go_addtags_transform', "snakecase")
" start constructing the command " start constructing the command
let cmd = [bin_path] let cmd = [bin_path]
call extend(cmd, ["-format", "json"]) call extend(cmd, ["-format", "json"])
call extend(cmd, ["-file", a:args.fname]) call extend(cmd, ["-file", a:args.fname])
call extend(cmd, ["-transform", l:modifytags_transform])
if l:offset != 0 if l:offset != 0
call extend(cmd, ["-offset", l:offset]) call extend(cmd, ["-offset", l:offset])

View file

@ -94,19 +94,29 @@ function! go#util#osarch() abort
return go#util#goos() . '_' . go#util#goarch() return go#util#goos() . '_' . go#util#goarch()
endfunction endfunction
" System runs a shell command. It will reset the shell to /bin/sh for Unix-like " System runs a shell command. If possible, it will temporary set
" systems if it is executable. " the shell to /bin/sh for Unix-like systems providing a Bourne
" POSIX like environment.
function! go#util#System(str, ...) abort function! go#util#System(str, ...) abort
" Preserve original shell and shellredir values
let l:shell = &shell let l:shell = &shell
let l:shellredir = &shellredir
" Use a Bourne POSIX like shell. Some parts of vim-go expect
" commands to be executed using bourne semantics #988 and #1276.
" Alter shellredir to match bourne. Especially important if login shell
" is set to any of the csh or zsh family #1276.
if !go#util#IsWin() && executable('/bin/sh') if !go#util#IsWin() && executable('/bin/sh')
let &shell = '/bin/sh' set shell=/bin/sh shellredir=>%s\ 2>&1
endif endif
try try
let l:output = call('system', [a:str] + a:000) let l:output = call('system', [a:str] + a:000)
return l:output return l:output
finally finally
" Restore original values
let &shell = l:shell let &shell = l:shell
let &shellredir = l:shellredir
endtry endtry
endfunction endfunction
@ -203,7 +213,7 @@ endfunction
" snippetcase converts the given word to given preferred snippet setting type " snippetcase converts the given word to given preferred snippet setting type
" case. " case.
function! go#util#snippetcase(word) abort function! go#util#snippetcase(word) abort
let l:snippet_case = get(g:, 'go_snippet_case_type', "snakecase") let l:snippet_case = get(g:, 'go_addtags_transform', "snakecase")
if l:snippet_case == "snakecase" if l:snippet_case == "snakecase"
return go#util#snakecase(a:word) return go#util#snakecase(a:word)
elseif l:snippet_case == "camelcase" elseif l:snippet_case == "camelcase"
@ -235,51 +245,6 @@ function! go#util#camelcase(word) abort
endif endif
endfunction endfunction
function! go#util#AddTags(line1, line2, ...) abort
" default is json
let l:keys = ["json"]
if a:0
let l:keys = a:000
endif
let l:line1 = a:line1
let l:line2 = a:line2
" If we're inside a struct and just call this function let us add the tags
" to all fields
" TODO(arslan): I don't like using patterns. Check if we can move it to
" `motion` and do it via AST based position
let ln1 = searchpair('struct {', '', '}', 'bcnW')
if ln1 == 0
echon "vim-go: " | echohl ErrorMsg | echon "cursor is outside the struct" | echohl None
return
endif
" searchpair only returns a single position
let ln2 = search('}', "cnW")
" if no range is given we apply for the whole struct
if l:line1 == l:line2
let l:line1 = ln1 + 1
let l:line2 = ln2 - 1
endif
for line in range(l:line1, l:line2)
" get the field name (word) that are not part of a commented line
let l:matched = matchstr(getline(line), '\(\/\/.*\)\@<!\w\+')
if empty(l:matched)
continue
endif
let word = go#util#snippetcase(l:matched)
let tags = map(copy(l:keys), 'printf("%s:%s", v:val,"\"'. word .'\"")')
let updated_line = printf("%s `%s`", getline(line), join(tags, " "))
" finally, update the line inplace
call setline(line, updated_line)
endfor
endfunction
" TODO(arslan): I couldn't parameterize the highlight types. Check if we can " TODO(arslan): I couldn't parameterize the highlight types. Check if we can
" simplify the following functions " simplify the following functions
" "

View file

@ -102,7 +102,7 @@ command.
Plugin 'fatih/vim-go' Plugin 'fatih/vim-go'
* Vim |packages| * Vim |packages|
> >
git clone https://github.com/fatih/vim-go.git \ git clone https://github.com/fatih/vim-go.git \
~/.vim/pack/plugins/start/vim-go ~/.vim/pack/plugins/start/vim-go
@ -167,7 +167,7 @@ COMMANDS *go-commands*
*:GoLint* *:GoLint*
:GoLint [packages] :GoLint [packages]
Run golint for the current Go file, or for given packages. Run golint for the current directory, or for given packages.
*:GoDoc* *:GoDoc*
:GoDoc [word] :GoDoc [word]
@ -219,14 +219,17 @@ COMMANDS *go-commands*
If [!] is not given the first error is jumped to. If [!] is not given the first error is jumped to.
*:GoDef* *:GoDef*
:GoDef :GoDef
gd gd
CTRL-] CTRL-]
g<C-LeftMouse>
<C-LeftMouse>
Goto declaration/definition for the declaration under the cursor. By default Goto declaration/definition for the declaration under the cursor. By
the CTRL-] key and the mapping `gd` are enabled to invoke :GoDef for the default the CTRL-] shortcut, the mapping `gd` and <C-LeftMouse>,
identifier under the cursor. See |'g:go_def_mapping_enabled'| to disable g<LeftMouse> are enabled to invoke :GoDef for the identifier under the
them. No explicit arguments are supported. cursor. See |'g:go_def_mapping_enabled'| to disable them. No explicit
arguments are supported.
vim-go also keeps a per-window location stack, roughly analogous to how vim-go also keeps a per-window location stack, roughly analogous to how
Vim's internal |tags| functionality works. This is pushed to every time a Vim's internal |tags| functionality works. This is pushed to every time a
@ -605,7 +608,7 @@ CTRL-t
Changes the build tags for various commands. If you have any file that Changes the build tags for various commands. If you have any file that
uses a custom build tag, such as `//+build integration` , this command can uses a custom build tag, such as `//+build integration` , this command can
be used to pass it to all tools that accepts tags, such as guru, gorenate, be used to pass it to all tools that accepts tags, such as guru, gorenate,
etc.. etc..
The build tags is cleared (unset) if `""` is given. If no arguments is The build tags is cleared (unset) if `""` is given. If no arguments is
given it prints the current custom build tags. given it prints the current custom build tags.
@ -742,7 +745,22 @@ CTRL-t
Toggles |'g:go_template_autocreate'|. Toggles |'g:go_template_autocreate'|.
*:GoKeyify*
:GoKeyify
Uses `keyify` to turn unkeyed struct literals into keyed ones.
For example:
>
Person{"John", "Smith"}
<
Becomes:
>
Person{
Name: "John",
Surname: "Smith",
}
<
============================================================================== ==============================================================================
MAPPINGS *go-mappings* MAPPINGS *go-mappings*
@ -1128,9 +1146,10 @@ Use this option to define the command to be used for |:GoDef|. By default
< <
*'g:go_def_mapping_enabled'* *'g:go_def_mapping_enabled'*
Use this option to enable/disable the default mapping of CTRL-] and (`gd`) for Use this option to enable/disable the default mapping of CTRL-],
GoDef and CTRL-t for :GoDefPop. Disabling it allows you to map something else <C-LeftMouse>, g<C-LeftMouse> and (`gd`) for GoDef and CTRL-t for :GoDefPop.
to these keys or mappings. Default is enabled. > Disabling it allows you to map something else to these keys or mappings.
Default is enabled. >
let g:go_def_mapping_enabled = 1 let g:go_def_mapping_enabled = 1
< <
@ -1169,28 +1188,6 @@ Use this option to define the default snippet engine. By default "ultisnips"
is used. Use "neosnippet" for neosnippet.vim: > is used. Use "neosnippet" for neosnippet.vim: >
let g:go_snippet_engine = "ultisnips" let g:go_snippet_engine = "ultisnips"
<
*'g:go_snippet_case_type'*
Use this option to define the default conversion type of snippet expansion for
field tags. For the following case, if `snakecase` is used the `json` snippet
will expand to:
>
type T struct {
FooBarQuz string `json:"foo_bar_quz"
}
<
If "camelcase" is used:
>
type T struct {
FooBarQuz string `json:"fooBarQuz"
}
<
By default "snakecase" is used. Current values are: ["snakecase",
"camelcase"].
>
let g:go_snippet_case_type = "snakecase"
< <
*'g:go_get_update'* *'g:go_get_update'*
@ -1213,7 +1210,7 @@ set, so the relevant commands defaults are being used.
*'g:go_build_tags'* *'g:go_build_tags'*
These options that will be automatically passed to the `-tags` option of These options that will be automatically passed to the `-tags` option of
various tools, such as `guru`, `gorename`, etc... This is a permanatent various tools, such as `guru`, `gorename`, etc... This is a permanent
setting. A more useful way is to use |:GoBuildTags| to dynamically change or setting. A more useful way is to use |:GoBuildTags| to dynamically change or
remove build tags. By default it's not set. remove build tags. By default it's not set.
> >
@ -1538,6 +1535,31 @@ default it's 60 seconds. Must be in milliseconds.
> >
let g:go_statusline_duration = 60000 let g:go_statusline_duration = 60000
< <
*'g:go_addtags_transform'*
Sets the `transform` option for `gomodifytags` when using |:GoAddTags| or if
it's being used for snippet expansion of single fields. Possible options are:
`snakecase`, `camelcase`. For the following case, if `snakecase` is used the
field will be transformed to:
>
type T struct {
FooBarQuz string `json:"foo_bar_quz"
}
<
If "camelcase" is used:
>
type T struct {
FooBarQuz string `json:"fooBarQuz"
}
<
By default "snakecase" is used. Current values are: ["snakecase",
"camelcase"].
>
let g:go_addtags_transform = 'snakecase'
<
============================================================================== ==============================================================================
DEVELOPMENT *go-development* DEVELOPMENT *go-development*

View file

@ -33,6 +33,8 @@ if get(g:, "go_def_mapping_enabled", 1)
" useful again for Go source code " useful again for Go source code
nnoremap <buffer> <silent> gd :GoDef<cr> nnoremap <buffer> <silent> gd :GoDef<cr>
nnoremap <buffer> <silent> <C-]> :GoDef<cr> nnoremap <buffer> <silent> <C-]> :GoDef<cr>
nnoremap <buffer> <silent> <C-LeftMouse> <LeftMouse>:GoDef<cr>
nnoremap <buffer> <silent> g<LeftMouse> <LeftMouse>:GoDef<cr>
nnoremap <buffer> <silent> <C-w><C-]> :<C-u>call go#def#Jump("split")<CR> nnoremap <buffer> <silent> <C-w><C-]> :<C-u>call go#def#Jump("split")<CR>
nnoremap <buffer> <silent> <C-w>] :<C-u>call go#def#Jump("split")<CR> nnoremap <buffer> <silent> <C-w>] :<C-u>call go#def#Jump("split")<CR>
nnoremap <buffer> <silent> <C-t> :<C-U>call go#def#StackPop(v:count1)<cr> nnoremap <buffer> <silent> <C-t> :<C-U>call go#def#StackPop(v:count1)<cr>

View file

@ -92,4 +92,7 @@ command! -nargs=* -buffer -complete=customlist,go#impl#Complete GoImpl call go#i
" -- template " -- template
command! -nargs=0 GoTemplateAutoCreateToggle call go#template#ToggleAutoCreate() command! -nargs=0 GoTemplateAutoCreateToggle call go#template#ToggleAutoCreate()
" -- keyify
command! -nargs=0 GoKeyify call go#keyify#Keyify()
" vim: sw=2 ts=2 et " vim: sw=2 ts=2 et

View file

@ -143,6 +143,13 @@ else {
} }
endsnippet endsnippet
# if inline error
snippet ife "If with inline erro"
if err := ${1:condition}; err != nil {
${0:${VISUAL}}
}
endsnippet
# error snippet # error snippet
snippet errn "Error return " !b snippet errn "Error return " !b
if err != nil { if err != nil {

View file

@ -118,6 +118,14 @@ snippet else
else { else {
${0} ${0}
} }
# if inline error
snippet ife
abbr if err := ...; err != nil { ... }
if err := ${1:condition}; err != nil {
${0}
}
# error snippet # error snippet
snippet errn snippet errn
abbr if err != nil { ... } abbr if err != nil { ... }

View file

@ -21,6 +21,7 @@ let s:packages = [
\ "github.com/fatih/gomodifytags", \ "github.com/fatih/gomodifytags",
\ "github.com/zmb3/gogetdoc", \ "github.com/zmb3/gogetdoc",
\ "github.com/josharian/impl", \ "github.com/josharian/impl",
\ "github.com/dominikh/go-tools/cmd/keyify",
\ ] \ ]
" These commands are available on any filetypes " These commands are available on any filetypes

View file

@ -97,7 +97,7 @@ exe 'syn region markdownBoldItalic matchgroup=markdownBoldItalicDelimiter start=
syn region markdownCode matchgroup=markdownCodeDelimiter start="`" end="`" keepend contains=markdownLineStart syn region markdownCode matchgroup=markdownCodeDelimiter start="`" end="`" keepend contains=markdownLineStart
syn region markdownCode matchgroup=markdownCodeDelimiter start="`` \=" end=" \=``" keepend contains=markdownLineStart syn region markdownCode matchgroup=markdownCodeDelimiter start="`` \=" end=" \=``" keepend contains=markdownLineStart
syn region markdownCode matchgroup=markdownCodeDelimiter start="^\s*```*.*$" end="^\s*```*\ze\s*$" keepend syn region markdownCode matchgroup=markdownCodeDelimiter start="^\s*````*.*$" end="^\s*````*\ze\s*$" keepend
syn match markdownFootnote "\[^[^\]]\+\]" syn match markdownFootnote "\[^[^\]]\+\]"
syn match markdownFootnoteDefinition "^\[^[^\]]\+\]:" syn match markdownFootnoteDefinition "^\[^[^\]]\+\]:"
@ -108,7 +108,7 @@ if main_syntax ==# 'markdown'
if has_key(s:done_include, matchstr(s:type,'[^.]*')) if has_key(s:done_include, matchstr(s:type,'[^.]*'))
continue continue
endif endif
exe 'syn region markdownHighlight'.substitute(matchstr(s:type,'[^=]*$'),'\..*','','').' matchgroup=markdownCodeDelimiter start="^\s*```*\s*'.matchstr(s:type,'[^=]*').'\>.*$" end="^\s*```*\ze\s*$" keepend contains=@markdownHighlight'.substitute(matchstr(s:type,'[^=]*$'),'\.','','g') exe 'syn region markdownHighlight'.substitute(matchstr(s:type,'[^=]*$'),'\..*','','').' matchgroup=markdownCodeDelimiter start="^\s*````*\s*'.matchstr(s:type,'[^=]*').'\S\@!.*$" end="^\s*````*\ze\s*$" keepend contains=@markdownHighlight'.substitute(matchstr(s:type,'[^=]*$'),'\.','','g')
let s:done_include[matchstr(s:type,'[^.]*')] = 1 let s:done_include[matchstr(s:type,'[^.]*')] = 1
endfor endfor
unlet! s:type unlet! s:type

View file

@ -0,0 +1,135 @@
priority -50
extends html
# We want to overwrite everything in parent ft.
priority -49
snippet break "@break"
@break
endsnippet
snippet component "@component directive"
@component('$1')
${2:${VISUAL}}
@endcomponent
endsnippet
snippet each "@each directive"
@each('$1', $$2, '$3')
endsnippet
snippet else "@else directive"
@else
endsnippet
snippet eif "@else if directive"
@else if ($1)
${2:${VISUAL}}
endsnippet
snippet for "@for directive"
@for ($1)
${2:${VISUAL}}
@endfor
endsnippet
snippet foreach "@foreach directive"
@foreach ($$1 as $$2)
${3:${VISUAL}}
@endforeach
endsnippet
snippet extends "@extends directive"
@extends('$1')
endsnippet
snippet if "@if directive"
@if ($1)
${2:${VISUAL}}
@endif
endsnippet
snippet ife "@if @else structure"
@if ($1)
${2:${VISUAL}}
@else
${3:${VISUAL}}
@endif
endsnippet
snippet include "@include directive"
@include('$1')
endsnippet
snippet includeIf "@includeIf directive"
@includeIf('$1')
endsnippet
snippet isset "@isset directive"
@isset
${1:${VISUAL}}
@endisset
endsnippet
snippet inject "@inject directive"
@inject('$1', '$2')
endsnippet
snippet php "@php directive"
@php
${1:${VISUAL}}
@endphp
endsnippet
snippet push "@push directive"
@push('$1')
${2:${VISUAL}}
@endpush
endsnippet
snippet section "@section directive"
@section('$1')
endsnippet
snippet show "@show directive"
@show
endsnippet
snippet slot "@slot directive"
@slot('$1')
${2:${VISUAL}}
@endslot
endsnippet
snippet unless "@unless directive"
@unless
${1:${VISUAL}}
@endunless
endsnippet
snippet verbatim "@verbatim directive"
@verbatim
${0:$VISUAL}
@endverbatim
endsnippet
snippet wh "@while directive"
@while ($1)
${2:${VISUAL}}
@endwhile
endsnippet
snippet yield "@yield directive"
@yield('$1')
endsnippet
snippet { "{{ }} statement."
{{ $1 }}
endsnippet
snippet {! "{!! !!} statement"
{!! $1 !!}
endsnippet
# vim:ft=snippets:

View file

@ -32,6 +32,18 @@ snippet escape "Escape (escape)"
&#x238B; &#x238B;
endsnippet endsnippet
snippet left "Left (left)"
&#x2190;
endsnippet
snippet return "Return (return)"
&#x21A9;
endsnippet
snippet right "Right (right)"
&#x2192;
endsnippet
snippet shift "Shift (shift)" snippet shift "Shift (shift)"
&#x21E7; &#x21E7;
endsnippet endsnippet
@ -44,67 +56,103 @@ snippet up "Up (up)"
&#x2191; &#x2191;
endsnippet endsnippet
snippet return "Return (return)"
&#x21A9;
endsnippet
snippet right "Right (right)"
&#x2192;
endsnippet
snippet left "Left (left)"
&#x2190;
endsnippet
############# #############
# HTML TAGS # # HTML TAGS #
############# #############
snippet input "Input with Label" w snippet a "Link" w
<label for="${2:${1/[[:alpha:]]+|( )/(?1:_:\L$0)/g}}">$1</label><input type="${3:text/submit/hidden/button}" name="${4:$2}" value="$5"${6: id="${7:$2}"}`!p x(snip)`> <a href="${1:http://www.${2:url.com}}"${3: target="_blank"}>${4:Anchor Text}</a>
endsnippet endsnippet
snippet input "HTML <input>" w snippet abbr "<abbr>" w
<input type="${1:text/submit/hidden/button}" name="${2:some_name}" value="$3"${4: id="${5:$2}"}`!p x(snip)`> <abbr title="$2">$1</abbr>
endsnippet endsnippet
snippet access "accesskey global attribute"
snippet option "Option" w accesskey="$1"
<option${1: value="${2:option}"}>${3:$2}</option>
endsnippet endsnippet
snippet select "Select Box" w snippet address "<address>" w
<select name="${1:some_name}" id="${2:$1}"${3:${4: multiple}${5: onchange="${6:}"}${7: size="${8:1}"}}> <address>$1</address>
${0:${VISUAL}}
</select>
endsnippet endsnippet
snippet article "<article>"
snippet textarea "HTML <textarea>" w <article>
<textarea name="${1:Name}" rows="${2:8}" cols="${3:40}">$0</textarea> ${1:article content}
</article>
endsnippet endsnippet
snippet mailto "HTML <a mailto: >" w snippet aside "<aside>"
<a href="mailto:${1:joe@example.com}?subject=${2:feedback}">${3:email me}</a> <aside>
${1:aside content}
</aside>
endsnippet
snippet b "<b>" w
<b>$1</b>
endsnippet endsnippet
snippet base "HTML <base>" w snippet base "HTML <base>" w
<base href="$1"${2: target="$3"}`!p x(snip)`> <base href="$1"${2: target="$3"}`!p x(snip)`>
endsnippet endsnippet
snippet blockquote "<blockquote>"
<blockquote>$1</blockquote>
endsnippet
snippet body "<body>" snippet body "<body>"
<body> <body>
${0:${VISUAL}} ${0:${VISUAL}}
</body> </body>
endsnippet endsnippet
snippet div "<div>" w snippet br "<br>" w
<div> <br>$1</br>
${0:${VISUAL}}
</div>
endsnippet endsnippet
snippet div. "<div> with class" w snippet button "<button>"
<div`!p snip.rv=' class="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""`> <button>$1</button>
endsnippet
snippet caption "<caption>"
<caption>$1</caption>
endsnippet
snippet cite "<cite>" w
<cite>$1</cite>
endsnippet
snippet class "class global attribute"
class="$1"
endsnippet
snippet code "<code>" w
<code>$1</code>
endsnippet
snippet data "<data>"
<data value="$2">$1</data>
endsnippet
snippet datalist "<datalist>"
<datalist id="$1" name="$2">
opt$3
</datalist>
endsnippet
snippet dd "<dd>"
<dd>$1</dd>
endsnippet
snippet del "<del>" w
<del cite="$2" datetime="${3:`date '+%Y-%m-%dT%H:%M:%S%:z'`}">$1</del>
endsnippet
snippet dfn "<dfn>" w
<dfn>$1</dfn>
endsnippet
snippet div "<div>" w
<div>
${0:${VISUAL}} ${0:${VISUAL}}
</div> </div>
endsnippet endsnippet
@ -115,120 +163,24 @@ snippet div# "<div> with ID & class" w
</div> </div>
endsnippet endsnippet
snippet form "XHTML <form>" w snippet div. "<div> with class" w
<form action="${1:`!p <div`!p snip.rv=' class="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""`>
snip.rv = (snip.basename or 'unnamed') + '_submit'
`}" method="${2:get}" accept-charset="utf-8">
${0:${VISUAL}} ${0:${VISUAL}}
</form> </div>
endsnippet endsnippet
snippet h1 "XHTML <h1>" w snippet dl "<dl>"
<h1>${0:${VISUAL}}</h1> <dl>
${1:Definition list}
</dl>
endsnippet endsnippet
snippet h2 "XHTML <h2>" w snippet dt "<dt>"
<h2>${0:${VISUAL}}</h2> <dt>$1</dt>
endsnippet endsnippet
snippet h3 "XHTML <h3>" w snippet em "<em>" w
<h3>${0:${VISUAL}}</h3> <em>$1</em>
endsnippet
snippet h4 "XHTML <h4>" w
<h4>${0:${VISUAL}}</h4>
endsnippet
snippet h5 "XHTML <h5>" w
<h5>${0:${VISUAL}}</h5>
endsnippet
snippet h6 "XHTML <h6>" w
<h6>${0:${VISUAL}}</h6>
endsnippet
snippet head "XHTML <head>"
<head>
<meta charset="utf-8">
<title>${1:`!p snip.rv = snip.basename or "Page Title"`}</title>
${0:${VISUAL}}
</head>
endsnippet
snippet link "XHTML <link>" w
<link rel="${1:stylesheet}" href="${2:/css/master.css}" type="text/css" media="${3:screen}" title="${4:no title}" charset="${5:utf-8}"`!p x(snip)`>
endsnippet
snippet meta "XHTML <meta>" w
<meta name="${1:name}" content="${2:content}"`!p x(snip)`>
endsnippet
snippet scriptsrc "HTML <script src...>" w
<script src="$1" charset="${3:utf-8}"></script>
endsnippet
snippet script "HTML <script>" w
<script charset="utf-8">
${0:${VISUAL}}
</script>
endsnippet
snippet span "<span>" w
<span> ${0:${VISUAL}} </span>
endsnippet
snippet span. "<span> with class" w
<span`!p snip.rv=' class="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""`> ${0:${VISUAL}} </span>
endsnippet
snippet span# "<span> with ID & class" w
<span`!p snip.rv=' id="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""``!p snip.rv=' class="' if t[2] else ""`${2:name}`!p snip.rv = '"' if t[2] else ""`> ${0:${VISUAL}} </span>
endsnippet
snippet style "XHTML <style>" w
<style type="text/css" media="screen">
${0:${VISUAL}}
</style>
endsnippet
snippet table "XHTML <table>" w
<table>
${0:${VISUAL}}
</table>
endsnippet
snippet a "Link" w
<a href="${1:http://www.${2:url.com}}"${3: target="_blank"}>${4:Anchor Text}</a>
endsnippet
snippet p "paragraph" w
<p>${0:${VISUAL}}</p>
endsnippet
snippet li "list item" w
<li>${0:${VISUAL}}</li>
endsnippet
snippet ul "unordered list" w
<ul>
${0:${VISUAL}}
</ul>
endsnippet
snippet td "table cell" w
<td>${0:${VISUAL}}</td>
endsnippet
snippet th "table header" w
<th>${0:${VISUAL}}</th>
endsnippet
snippet tr "table row" w
<tr>${0:${VISUAL}}</tr>
endsnippet
snippet title "XHTML <title>" w
<title>${1:`!p snip.rv = snip.basename or "Page Title"`}</title>
endsnippet endsnippet
snippet fieldset "Fieldset" w snippet fieldset "Fieldset" w
@ -238,7 +190,341 @@ snippet fieldset "Fieldset" w
</fieldset> </fieldset>
endsnippet endsnippet
snippet fig "<figure>"
<figure>
$1
<figcaption>$2</figcaption>
</figure>
endsnippet
snippet figcaption "<figcaption>"
<figcaption>$1</figcaption>
endsnippet
snippet footer "<footer>"
<footer>
${1:footer content}
</footer>
endsnippet
snippet form "HTML <form>" w
<form action="${1:`!p
snip.rv = (snip.basename or 'unnamed') + '_submit'
`}" method="${2:get}" accept-charset="utf-8">
${0:${VISUAL}}
</form>
endsnippet
snippet h1 "HTML <h1>" w
<h1>${0:${VISUAL}}</h1>
endsnippet
snippet h2 "HTML <h2>" w
<h2>${0:${VISUAL}}</h2>
endsnippet
snippet h3 "HTML <h3>" w
<h3>${0:${VISUAL}}</h3>
endsnippet
snippet h4 "HTML <h4>" w
<h4>${0:${VISUAL}}</h4>
endsnippet
snippet h5 "HTML <h5>" w
<h5>${0:${VISUAL}}</h5>
endsnippet
snippet h6 "HTML <h6>" w
<h6>${0:${VISUAL}}</h6>
endsnippet
snippet head "HTML <head>"
<head>
<meta charset="utf-8">
<title>${1:`!p snip.rv = snip.basename or "Page Title"`}</title>
${0:${VISUAL}}
</head>
endsnippet
snippet header "<header>"
<header>
${1:header content}
</header>
endsnippet
snippet hr "<hr>"
<hr>
endsnippet
snippet html "HTML basic structure" b
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>${1:`!p snip.rv = snip.basename.replace('-', ' ').capitalize()`}</title>
</head>
<body>
${0:body}
</body>
</html>
endsnippet
snippet htmll "HTML basic structure with the lang attribute" b
<!DOCTYPE html>
<html lang="${1:es}">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>${2:`!p snip.rv = snip.basename.replace('-', ' ').capitalize()`}</title>
</head>
<body>
${0:body}
</body>
</html>
endsnippet
snippet i "<i>" w
<i>$1</i>
endsnippet
snippet id "id global attribute"
id="$1"
endsnippet
snippet img "<img>"
<img src="$1" alt="$2">
endsnippet
snippet input "Input with Label" w
<label for="${2:${1/[[:alpha:]]+|( )/(?1:_:\L$0)/g}}">$1</label><input type="${3:text/submit/hidden/button}" name="${4:$2}" value="$5"${6: id="${7:$2}"}`!p x(snip)`>
endsnippet
snippet input "HTML <input>" w
<input type="${1:text/submit/hidden/button}" name="${2:some_name}" value="$3"${4: id="${5:$2}"}`!p x(snip)`>
endsnippet
snippet ins "<ins>" w
<ins cite="$2" datetime="${3:`date '+%Y-%m-%dT%H:%M:%S%:z'`}">$1</ins>
endsnippet
snippet kbd "<kbd>" w
<kbd>$1</kbd>
endsnippet
snippet label "<label>"
<label>$1</label>
endsnippet
snippet legend "<legend>"
<legend>$1</leyend>
endsnippet
snippet li "list item" w
<li>${0:${VISUAL}}</li>
endsnippet
snippet link "HTML <link>" w
<link rel="${1:stylesheet}" href="${2:/css/master.css}" type="text/css" media="${3:screen}" title="${4:no title}" charset="${5:utf-8}"`!p x(snip)`>
endsnippet
snippet mailto "HTML <a mailto: >" w
<a href="mailto:${1:joe@example.com}?subject=${2:feedback}">${3:email me}</a>
endsnippet
snippet main "<main>"
<main>
${1:main content}
</main>
endsnippet
snippet mark "<mark>"
<mark>$1</mark>
endsnippet
snippet meta "HTML <meta>" w
<meta name="${1:name}" content="${2:content}"`!p x(snip)`>
endsnippet
snippet meter "<meter>"
<meter>$1</meter>
endsnippet
snippet nav "<nav>"
<nav>
${1:navigation links}
</nav>
endsnippet
snippet noscript "<noscript>"
<noscript>$1</noscript>
endsnippet
snippet ol "<ol>"
<ol>
<li>$1</li>
</ol>
endsnippet
snippet optgroup "<optgroup>"
<optgroup label="$1">
opt$2
</optgroup>
endsnippet
snippet output "<output>"
<output for="$1" name="$2">$3</output>
endsnippet
snippet option "Option" w
<option${1: value="${2:option}"}>${3:$2}</option>
endsnippet
snippet p "paragraph" w
<p>${0:${VISUAL}}</p>
endsnippet
snippet picture "<picture>"
<picture>
${1:image sources}
</picture>
endsnippet
snippet pre "<pre>"
<pre>$1</pre>
endsnippet
snippet progress "<progress>"
<progress>$1</progress>
endsnippet
snippet q "<q>" w
<q>$1</q>
endsnippet
snippet s "<s>" w
<s>$1</s>
endsnippet
snippet samp "<samp>" w
<samp>$1</samp>
endsnippet
snippet script "HTML <script>" w
<script charset="utf-8">
${0:${VISUAL}}
</script>
endsnippet
snippet scriptsrc "HTML <script src...>" w
<script src="$1" charset="${3:utf-8}"></script>
endsnippet
snippet select "Select Box" w
<select name="${1:some_name}" id="${2:$1}"${3:${4: multiple}${5: size="${6:1}"}}>
${0:${VISUAL}}
</select>
endsnippet
snippet small "<small>" w
<small>$1</small>
endsnippet
snippet span "<span>" w
<span> ${0:${VISUAL}} </span>
endsnippet
snippet span# "<span> with ID & class" w
<span`!p snip.rv=' id="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""``!p snip.rv=' class="' if t[2] else ""`${2:name}`!p snip.rv = '"' if t[2] else ""`> ${0:${VISUAL}} </span>
endsnippet
snippet span. "<span> with class" w
<span`!p snip.rv=' class="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""`> ${0:${VISUAL}} </span>
endsnippet
snippet strong "<strong>" w
<strong>$1</strong>
endsnippet
snippet style "HTML <style>" w
<style type="text/css" media="screen">
${0:${VISUAL}}
</style>
endsnippet
snippet sub "<sub>" w
<sub>$1</sub>
endsnippet
snippet sup "<sup>" w
<sup>$1</sup>
endsnippet
snippet table "HTML <table>" w
<table>
${0:${VISUAL}}
</table>
endsnippet
snippet tbody "<tbody>"
<tbody>$1</tbody>
endsnippet
snippet td "table cell" w
<td>${0:${VISUAL}}</td>
endsnippet
snippet template "<template>"
<template id="$1">
$2
</template>
endsnippet
snippet textarea "HTML <textarea>" w
<textarea name="${1:Name}" rows="${2:8}" cols="${3:40}">$0</textarea>
endsnippet
snippet tfoot "<tfoot>"
<tfoot>$1</tfoot>
endsnippet
snippet th "table header" w
<th>${0:${VISUAL}}</th>
endsnippet
snippet thead "<thead>"
<thead>$1</thead>
endsnippet
snippet time "<time>" w
<time datetime="$2">$1</time>
endsnippet
snippet title "HTML <title>" w
<title>${1:`!p snip.rv = snip.basename or "Page Title"`}</title>
endsnippet
snippet tr "table row" w
<tr>${0:${VISUAL}}</tr>
endsnippet
snippet ul "unordered list" w
<ul>
${0:${VISUAL}}
</ul>
endsnippet
snippet var "<var>" w
<var>$1</var>
endsnippet
snippet viewport "Responsive viewport meta" w snippet viewport "Responsive viewport meta" w
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
endsnippet endsnippet
snippet wbr "<wbr>" w
<wbr>$1</wbr>
endsnippet
# vim:ft=snippets: # vim:ft=snippets:

View file

@ -8,6 +8,12 @@ snippet "b(egin)?" "begin{} / end{}" br
\end{$1} \end{$1}
endsnippet endsnippet
snippet abs "abstract environment" b
\begin{abstract}
$0
\end{abstract}
endsnippet
snippet tab "tabular / array environment" b snippet tab "tabular / array environment" b
\begin{${1:t}${1/(t)$|(a)$|(.*)/(?1:abular)(?2:rray)/}}{${2:c}} \begin{${1:t}${1/(t)$|(a)$|(.*)/(?1:abular)(?2:rray)/}}{${2:c}}
$0${2/(?<=.)(c|l|r)|./(?1: & )/g} $0${2/(?<=.)(c|l|r)|./(?1: & )/g}

View file

@ -133,10 +133,9 @@ snippet BSD2
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation The views and conclusions contained in the software and documentation
are those of the authors and should not be interpreted as representing are those of the authors and should not be interpreted as representing
official policies, either expressedor implied, of $2. official policies, either expressed or implied, of $2.
${0} ${0}
snippet BSD3 snippet BSD3
${1:one line to give the program's name and a brief description} ${1:one line to give the program's name and a brief description}

View file

@ -1,7 +1,14 @@
# Shebang. Executing bash via /usr/bin/env makes scripts more portable. # Shebang. Executing bash via /usr/bin/env makes scripts more portable.
snippet #! snippet #!
#!/usr/bin/env sh #!/usr/bin/env sh
snippet s#!
#!/usr/bin/env sh
set -euo pipefail
snippet safe
set -euo pipefail
snippet bash snippet bash
#!/usr/bin/env bash #!/usr/bin/env bash

View file

@ -0,0 +1 @@
extends javascript

View file

@ -0,0 +1 @@
extends html, javascript, css

View file

@ -51,6 +51,7 @@ vim-flake8 https://github.com/nvie/vim-flake8
vim-pug https://github.com/digitaltoad/vim-pug vim-pug https://github.com/digitaltoad/vim-pug
vim-yankstack https://github.com/maxbrunsfeld/vim-yankstack vim-yankstack https://github.com/maxbrunsfeld/vim-yankstack
lightline.vim https://github.com/itchyny/lightline.vim lightline.vim https://github.com/itchyny/lightline.vim
vim-abolish https://github.com/tpope/vim-abolish
""".strip() """.strip()
GITHUB_ZIP = '%s/archive/master.zip' GITHUB_ZIP = '%s/archive/master.zip'