Compare commits

...

75 Commits

Author SHA1 Message Date
Adam Stankiewicz
d51b8fd17e Change handlebars syntax vendor, fixes #13 2014-02-04 19:15:58 +01:00
Adam Stankiewicz
fa57320919 Update 2014-02-04 19:13:11 +01:00
Adam Stankiewicz
9a2b4f5cd8 Update 2014-01-24 18:06:22 +01:00
Adam Stankiewicz
f211f02d1e Update 2014-01-09 11:59:09 +01:00
Adam Stankiewicz
e45b23b6ee Allow for reusing vim server locally (testing) 2013-12-27 16:44:34 +01:00
Adam Stankiewicz
a0c5f3ee55 Try to not reuse server for Travis 2013-12-27 16:40:01 +01:00
Adam Stankiewicz
6b8c72637f Set timeout on test cases 2013-12-27 00:06:18 +01:00
Adam Stankiewicz
d330fdc01b Update scala 2013-12-27 00:01:27 +01:00
Adam Stankiewicz
c225bf8826 fix: For some reason stylus test hangs on travis 2013-12-27 00:01:14 +01:00
Adam Stankiewicz
20125ac3ac fix: For some reason stylus test hangs on travis 2013-12-26 23:42:00 +01:00
Adam Stankiewicz
9f19823a30 Enable verbose testing 2013-12-26 23:13:05 +01:00
Adam Stankiewicz
56d5fc498b Test all possible file extensions, fixes #7 2013-12-26 23:03:02 +01:00
Adam Stankiewicz
ab679f37dd Replace css-color with vim-coloresque, closes #11 2013-12-26 21:09:58 +01:00
Adam Stankiewicz
ca95a47a93 Change strategy to appending instead of copying 2013-12-26 04:05:26 +01:00
Adam Stankiewicz
a26bebbeb9 Update 2013-12-26 03:34:22 +01:00
Adam Stankiewicz
edd5ee63e6 Update 2013-12-13 01:37:01 +01:00
Adam Stankiewicz
8a255002df Update csv and rust 2013-11-11 01:34:19 +01:00
Adam Stankiewicz
b2d556d384 Update latex, ruby and mason 2013-11-06 23:55:01 +01:00
Adam Stankiewicz
30c1920e4f Massive update :) 2013-11-02 23:27:57 +01:00
Adam Stankiewicz
57cfac7ae3 Update latex, csv, handlebars and rust 2013-10-17 15:54:18 +02:00
Adam Stankiewicz
085aad28a4 Update latex complete.vim 2013-10-08 12:04:23 +02:00
Adam Stankiewicz
e108a087b4 Update latex, html, ruby, c, cpp 2013-10-07 11:07:27 +02:00
Adam Stankiewicz
b3257271db Add R language support 2013-09-30 12:05:56 +02:00
Adam Stankiewicz
e9d8c39608 Update coffee, html and latex 2013-09-30 12:03:06 +02:00
Adam Stankiewicz
04e6a8a73c Update latex 2013-09-28 21:55:04 +02:00
Adam Stankiewicz
b6a2261cc2 Update rust and latex 2013-09-27 10:21:44 +02:00
Adam Stankiewicz
811fe888a6 Ignore more files in .zip releases 2013-09-26 13:20:32 +02:00
Adam Stankiewicz
2b19388166 Add dockerfile syntax support 2013-09-26 12:48:01 +02:00
Adam Stankiewicz
a531f6b104 Update languages list in the README 2013-09-26 12:45:26 +02:00
Adam Stankiewicz
90d87abd30 Add Rust lang support 2013-09-26 12:44:31 +02:00
Adam Stankiewicz
d6710f1b57 Add TypeScript support 2013-09-26 12:41:08 +02:00
Adam Stankiewicz
0db9bdbfd6 Update latex ftplugin 2013-09-26 12:40:21 +02:00
Adam Stankiewicz
c069f0661a Update clojure, tex and coffee 2013-09-22 23:24:04 +02:00
Adam Stankiewicz
235a5631f9 Update latex-box and elixir 2013-09-18 22:51:23 +02:00
Adam Stankiewicz
edf1aa4a1c Update jade syntax 2013-09-17 18:15:18 +02:00
Adam Stankiewicz
88bd82d6c9 Merge pull request #10 from hoelzro/master
Add Perl language files
2013-09-17 09:14:18 -07:00
Rob Hoelz
2686fb60f4 Add Perl language files 2013-09-17 17:37:59 +02:00
Adam Stankiewicz
9d92f10375 Use my own fork of rspec.vim to properly detect spec file 2013-09-17 02:43:05 +02:00
Adam Stankiewicz
fc0b11afe1 Remove tpope/vim-bundler as it does not include syntax 2013-09-17 02:17:15 +02:00
Adam Stankiewicz
0fcd056648 fix: Switch erlang to oscarh/vimerl (it doesnt use plugin dir) 2013-09-17 02:02:37 +02:00
Adam Stankiewicz
78cd7e48cb List possible failing plugins 2013-09-17 01:53:14 +02:00
Adam Stankiewicz
ba1305772d fix: Switch latex to LaTeX-Box-Team/LaTeX-Box, fixes #6 2013-09-17 01:43:28 +02:00
Adam Stankiewicz
ff3cc42bf3 Minor cleanup in build file 2013-09-16 17:46:24 +02:00
Adam Stankiewicz
e69f9f91d9 fix: README formatting 2013-09-16 17:02:09 +02:00
Adam Stankiewicz
c37e16fbbd Mention about real startup cost 2013-09-16 16:59:43 +02:00
Adam Stankiewicz
d7873996b4 Concat ftdetect scripts and mention startup cost in the README 2013-09-16 16:54:16 +02:00
Adam Stankiewicz
73cbf0269e Merge pull request #5 from bitdeli-chef/master
Add a Bitdeli Badge to README
2013-09-16 01:00:53 -07:00
Bitdeli Chef
0077bd5a31 Add a Bitdeli badge to README 2013-09-16 08:00:48 +00:00
Adam Stankiewicz
e8c16931f9 Update stylus and clojure syntaxes 2013-09-16 02:07:41 +02:00
Adam Stankiewicz
752a647be1 fix: Use bash for build script 2013-09-14 20:48:46 +02:00
Adam Stankiewicz
97a0bdcef6 fix: Build spec, use bash, check return status 2013-09-14 20:46:47 +02:00
Adam Stankiewicz
58f119c57f Fix url in the README
[skip ci]
2013-09-14 20:43:34 +02:00
Adam Stankiewicz
0ac0389039 Add simple spec for build script 2013-09-14 20:42:27 +02:00
Adam Stankiewicz
4bf3f6c300 Add travis badge and additional info in features 2013-09-14 20:30:57 +02:00
Adam Stankiewicz
4a80e945ad Add Travis CI integration 2013-09-14 20:23:24 +02:00
Adam Stankiewicz
27f22774b1 Move specs location one level down 2013-09-14 20:20:59 +02:00
Adam Stankiewicz
f6be1d3d13 Reorganize build script a little 2013-09-14 20:10:55 +02:00
Adam Stankiewicz
77f091c8c7 Add specs to be sure all plugins are loading properly 2013-09-14 20:09:32 +02:00
Adam Stankiewicz
17149b4657 Update tomdoc repository in the README, fixes #3 2013-09-14 18:22:55 +02:00
Adam Stankiewicz
271c88a356 fix: Add jade to list of supported languages in README 2013-09-14 18:22:17 +02:00
Adam Stankiewicz
b86a0cd422 fix: Update PHP repository name in the README 2013-09-14 18:21:47 +02:00
Adam Stankiewicz
06c80c676e Switch to StanAngeloff/php.vim as spf13/PIV relies on plugin stuff, fixes #4 2013-09-14 18:12:31 +02:00
Adam Stankiewicz
b061a2d995 Merge pull request #3 from duwanis/use_official_tomdoc_vim
Use the official tomdoc.vim repository
2013-09-14 08:52:35 -07:00
Tommy Morgan
e59b949def Use the official tomdoc.vim repository
https://github.com/duwanis/tomdoc.vim is the offical tomdoc.vim repo,
and has a few extra changes in it that mutewinter's fork does not. This
commit adjusts the readme and updates the after/coffee.vim and
after/ruby.vim files to reflect the latest changes for this plugin.
2013-09-14 09:46:15 -04:00
Adam Stankiewicz
f0d869aea7 Add jade template syntax support, closes #2 2013-09-14 11:38:54 +02:00
Adam Stankiewicz
96e9c416ae Add protobuf format support, closes #2 2013-09-14 11:38:00 +02:00
Adam Stankiewicz
d888bc4422 Mention in readme which subdirs were merged per plugin 2013-09-13 22:12:52 +02:00
Adam Stankiewicz
b4425d2c39 Generate supported languages automatically 2013-09-13 21:35:46 +02:00
Adam Stankiewicz
1ef902d053 Cleanup in supported languages 2013-09-13 21:25:08 +02:00
Adam Stankiewicz
ea97d9a230 Update readme and release v1.1 2013-09-13 18:22:24 +02:00
Adam Stankiewicz
db99bf52d3 Add extended c/c++ syntax, closes #1 2013-09-13 18:18:09 +02:00
Adam Stankiewicz
bbe1308b2f Add support for highlighting css colors 2013-09-13 17:33:23 +02:00
Adam Stankiewicz
8b5607d0f7 Add html5 support 2013-09-13 17:30:58 +02:00
Adam Stankiewicz
303837b5be Add latex support 2013-09-13 17:28:18 +02:00
Adam Stankiewicz
3e9a36e388 @tpope uses vbnet syntax, I shall respect that 2013-09-13 17:19:09 +02:00
151 changed files with 19699 additions and 9022 deletions

4
.gitattributes vendored
View File

@@ -2,3 +2,7 @@
.gitattributes export-ignore
build export-ignore
README.md export-ignore
/spec export-ignore
Gemfile export-ignore
Gemfile.lock export-ignore
.travis.yml export-ignore

8
.travis.yml Normal file
View File

@@ -0,0 +1,8 @@
language: ruby
rvm:
- 1.9.3
before_install: sudo apt-get install vim-gtk
before_script:
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
script: bundle exec rspec --format=documentation

4
Gemfile Normal file
View File

@@ -0,0 +1,4 @@
source 'https://rubygems.org'
gem 'vimrunner'
gem 'rspec'

20
Gemfile.lock Normal file
View File

@@ -0,0 +1,20 @@
GEM
remote: https://rubygems.org/
specs:
diff-lcs (1.1.3)
rspec (2.12.0)
rspec-core (~> 2.12.0)
rspec-expectations (~> 2.12.0)
rspec-mocks (~> 2.12.0)
rspec-core (2.12.2)
rspec-expectations (2.12.1)
diff-lcs (~> 1.1.3)
rspec-mocks (2.12.0)
vimrunner (0.3.0)
PLATFORMS
ruby
DEPENDENCIES
rspec
vimrunner

View File

@@ -1,14 +1,20 @@
# vim-polyglot
# vim-polyglot [![Build Status][travis-img-url]][travis-url]
[travis-img-url]: https://travis-ci.org/sheerun/vim-polyglot.png
[travis-url]: https://travis-ci.org/sheerun/vim-polyglot
A collection of language packs for Vim.
One to rule them all, one to find them, one to bring them all and in the darkness bind them.
- It **won't affect your startup time**, as all files are loaded only on demand.
- It **won't affect your startup time**, as scripts are loaded only on demand\*.
- It **installs 40x faster** (unparallelized), as language packs are not submoduled, but merged.
- It clones even faster as all unnecessary files are ignored (like enormous documentation from php support).
- Best syntax and indentation support. If someone releases better language pack, it will be replaced here.
- No support for esoteric languages (vim-polyglot supports modern ones like `slim` though).
- Each build is tested by automated Travis CI setup using vimrunner gem. Spee `spec` directory.
\*To be completely honest, concatenated `ftdetect` script takes around `3ms` to load.
## Installation
@@ -19,42 +25,53 @@ Optionally download one of the [releases](https://github.com/sheerun/vim-polyglo
## Language packs
- [arduino](https://github.com/sudar/vim-arduino-syntax)
- [bundler](https://github.com/tpope/vim-bundler)
- [clojure](https://github.com/guns/vim-clojure-static)
- [coffee-script](https://github.com/kchmck/vim-coffee-script)
- [csv](https://github.com/chrisbra/csv.vim)
- [cucumber](https://github.com/tpope/vim-cucumber)
- [elixir](https://github.com/elixir-lang/vim-elixir)
- [erlang](https://github.com/jimenezrick/vimerl)
- [git](https://github.com/tpope/vim-git)
- [haml](https://github.com/tpope/vim-haml)
- [handlebars](https://github.com/nono/vim-handlebars)
- [hasksyn](https://github.com/travitch/hasksyn)
- [javascript](https://github.com/pangloss/vim-javascript)
- [json](https://github.com/leshill/vim-json)
- [jst](https://github.com/briancollins/vim-jst)
- [less](https://github.com/groenewege/vim-less)
- [markdown](https://github.com/tpope/vim-markdown)
- [nginx](https://github.com/mutewinter/nginx.vim)
- [ocaml](https://github.com/jrk/vim-ocaml)
- [octave](https://github.com/vim-scripts/octave.vim--)
- [php](https://github.com/spf13/PIV)
- [puppet](https://github.com/ajf/puppet-vim)
- [python](https://github.com/vim-scripts/python.vim--Vasiliev)
- [rspec](https://github.com/skwp/vim-rspec)
- [ruby](https://github.com/vim-ruby/vim-ruby)
- [sbt](https://github.com/derekwyatt/vim-sbt)
- [scala](https://github.com/derekwyatt/vim-scala)
- [scss-syntax](https://github.com/cakebaker/scss-syntax.vim)
- [slim](https://github.com/slim-template/vim-slim)
- [stylus](https://github.com/wavded/vim-stylus)
- [textile](https://github.com/timcharper/textile.vim)
- [tmux](https://github.com/acustodioo/vim-tmux)
- [tomdoc](https://github.com/mutewinter/tomdoc.vim)
- [twig](https://github.com/beyondwords/vim-twig)
- [vim-golang](https://github.com/jnwhiteh/vim-golang)
- [xls](https://github.com/vim-scripts/XSLT-syntax)
- [arduino](https://github.com/sudar/vim-arduino-syntax) (syntax, ftdetect)
- [c++11](https://github.com/octol/vim-cpp-enhanced-highlight) (syntax)
- [c/c++](https://github.com/vim-jp/cpp-vim) (syntax)
- [clojure](https://github.com/guns/vim-clojure-static) (syntax, indent, autoload, ftplugin, ftdetect)
- [coffee-script](https://github.com/kchmck/vim-coffee-script) (syntax, indent, compiler, autoload, ftplugin, ftdetect)
- [css-color](https://github.com/gorodinskiy/vim-coloresque) (syntax)
- [csv](https://github.com/chrisbra/csv.vim) (syntax, ftplugin, ftdetect)
- [cucumber](https://github.com/tpope/vim-cucumber) (syntax, indent, compiler, ftplugin, ftdetect)
- [dockerfile](https://github.com/honza/dockerfile.vim) (syntax, ftdetect)
- [elixir](https://github.com/elixir-lang/vim-elixir) (syntax, indent, compiler, ftplugin, ftdetect)
- [erlang](https://github.com/oscarh/vimerl) (syntax, indent, compiler, autoload, ftplugin)
- [git](https://github.com/tpope/vim-git) (syntax, indent, ftplugin, ftdetect)
- [go](https://github.com/jnwhiteh/vim-golang) (syntax, indent, autoload, ftplugin, ftdetect)
- [haml](https://github.com/tpope/vim-haml) (syntax, indent, compiler, ftplugin, ftdetect)
- [handlebars](https://github.com/nono/vim-handlebars) (syntax, ftplugin, ftdetect)
- [haskell](https://github.com/travitch/hasksyn) (syntax, indent, ftplugin)
- [html5](https://github.com/othree/html5.vim) (syntax, indent, autoload)
- [jade](https://github.com/digitaltoad/vim-jade) (syntax, indent, ftplugin, ftdetect)
- [javascript](https://github.com/pangloss/vim-javascript) (syntax, indent, ftdetect)
- [json](https://github.com/leshill/vim-json) (syntax, ftdetect)
- [jst](https://github.com/briancollins/vim-jst) (syntax, indent, ftdetect)
- [latex](https://github.com/LaTeX-Box-Team/LaTeX-Box) (syntax, indent, ftplugin)
- [less](https://github.com/groenewege/vim-less) (syntax, indent, ftplugin, ftdetect)
- [markdown](https://github.com/tpope/vim-markdown) (syntax, ftplugin, ftdetect)
- [nginx](https://github.com/mutewinter/nginx.vim) (syntax, ftdetect)
- [ocaml](https://github.com/jrk/vim-ocaml) (syntax, indent, ftplugin)
- [octave](https://github.com/vim-scripts/octave.vim--) (syntax)
- [perl](https://github.com/vim-perl/vim-perl) (syntax, indent, ftplugin)
- [php](https://github.com/StanAngeloff/php.vim) (syntax)
- [puppet](https://github.com/ajf/puppet-vim) (syntax, indent, ftplugin, ftdetect)
- [protobuf](https://github.com/uarun/vim-protobuf) (syntax, ftdetect)
- [python](https://github.com/vim-scripts/python.vim--Vasiliev) (syntax)
- [r-lang](https://github.com/vim-scripts/R.vim) (syntax, ftplugin)
- [rspec](https://github.com/sheerun/rspec.vim) (syntax, ftdetect)
- [ruby](https://github.com/vim-ruby/vim-ruby) (syntax, indent, compiler, autoload, ftplugin, ftdetect)
- [rust](https://github.com/wting/rust.vim) (syntax, indent, compiler, ftplugin, ftdetect)
- [sbt](https://github.com/derekwyatt/vim-sbt) (syntax, ftdetect)
- [scala](https://github.com/derekwyatt/vim-scala) (syntax, indent, ftplugin, ftdetect)
- [slim](https://github.com/slim-template/vim-slim) (syntax, indent, ftdetect)
- [stylus](https://github.com/wavded/vim-stylus) (syntax, indent, ftplugin, ftdetect)
- [textile](https://github.com/timcharper/textile.vim) (syntax, ftplugin, ftdetect)
- [tmux](https://github.com/acustodioo/vim-tmux) (syntax, ftdetect)
- [tomdoc](https://github.com/duwanis/tomdoc.vim) (syntax)
- [typescript](https://github.com/leafgarland/typescript-vim) (syntax, compiler, ftplugin, ftdetect)
- [vbnet](https://github.com/vim-scripts/vbnet.vim) (syntax)
- [twig](https://github.com/beyondwords/vim-twig) (syntax, ftplugin, ftdetect)
- [xls](https://github.com/vim-scripts/XSLT-syntax) (syntax)
## Contributing
@@ -65,3 +82,7 @@ Feel free to add your language, and send pull-request.
## License
See linked repositories for detailed license information.
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/sheerun/vim-polyglot/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

2
after/ftdetect/rspec.vim Normal file
View File

@@ -0,0 +1,2 @@
autocmd BufReadPost,BufNewFile *_spec.rb set syntax=rspec
autocmd BufReadPost,BufNewFile *_spec.rb setlocal commentstring=#\ %s

View File

@@ -1,24 +0,0 @@
if !exists("g:DisableAutoPHPFolding")
let g:DisableAutoPHPFolding = 0
endif
if !g:DisableAutoPHPFolding
" Don't use the PHP syntax folding
setlocal foldmethod=manual
" Turn on PHP fast folds
EnableFastPHPFolds
endif
" Fix matchpairs for PHP (for matchit.vim plugin)
if exists("loaded_matchit")
let b:match_skip = 's:comment\|string'
let b:match_words = '<?\(php\)\?:?>,\<switch\>:\<endswitch\>,' .
\ '\<if\>:\<elseif\>:\<else\>:\<endif\>,' .
\ '\<while\>:\<endwhile\>,\<do\>:\<while\>,' .
\ '\<for\>:\<endfor\>,\<foreach\>:\<endforeach\>' .
\ '<\@<=[ou]l\>[^>]*\%(>\|$\):<\@<=li\>:<\@<=/[ou]l>,' .
\ '<\@<=dl\>[^>]*\%(>\|$\):<\@<=d[td]\>:<\@<=/dl>,' .
\ '<\@<=\([^/?][^ \t>]*\)[^>]*\%(>\|$\):<\@<=/\1>,' .
\ '<:>,(:),{:},[:]'
endif

View File

@@ -4,12 +4,12 @@
" License: WTFPL
" Load the coffee and html indent functions.
unlet b:did_indent
silent! unlet b:did_indent
runtime indent/coffee.vim
let s:coffeeIndentExpr = &l:indentexpr
" Load html last so it can overwrite coffee settings.
unlet b:did_indent
silent! unlet b:did_indent
runtime indent/html.vim
let s:htmlIndentExpr = &l:indentexpr

View File

@@ -5,8 +5,7 @@
"
syn keyword tomdocKeywords Returns containedin=coffeeComment contained
syn keyword tomdocKeywords Yields containedin=coffeeComment contained
syn keyword tomdocKeywords Raises containedin=coffeeComment contained
syn keyword tomdocKeywords Throws containedin=coffeeComment contained
syn keyword tomdocKeywords Examples containedin=coffeeComment contained
syn keyword tomdocKeywords Signature containedin=coffeeComment contained
@@ -16,6 +15,6 @@ syn match tomdocDescriptions +\s*Public:+he=e-1 containedin=coffeeComment contai
syn match tomdocDescriptions +\s*Internal:+he=e-1 containedin=coffeeComment contained
syn match tomdocDescriptions +\s*Deprecated:+he=e-1 containedin=coffeeComment contained
hi default link tomdocDescriptions TODO
hi default link tomdocKeywords TODO
hi default link tomdocDescriptions String
hi default link tomdocKeywords String
hi default link tomdocArguments HELP

1290
after/syntax/cpp.vim Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,632 @@
" Name: Coloresque
" Language: color preview in vim
" Author: Gorodinskii Konstantin <gor.konstantin@gmail.com>
" Licence: Vim license
" Version: 0.9.5
" based on
" https://github.com/ap/vim-css-color
" https://github.com/lilydjwg/colorizer
" vim:et:ts=2 sw=2 sts=2
let s:hex={}
let b:matchescache = {}
let b:color_pattern = {}
let w:colorDictRegExp=''
for i in range(0, 255)
let s:hex[ printf( '%02x', i ) ] = i
endfor
let s:black = '#000000'
let s:white = '#ffffff'
function! s:FGForBG(color)
" pick suitable text color given a background color
let color = tolower(a:color)
let r = s:hex[color[0:1]]
let g = s:hex[color[2:3]]
let b = s:hex[color[4:5]]
return r*30 + g*59 + b*11 > 12000 ? s:black : s:white
endfunction
let s:color_prefix = 'gui'
let s:fg_color_calc = 'let color = "#" . toupper(a:color)'
function! s:RestoreColors()
for part in keys(b:color_pattern)
"if b:color_pattern[part]=="ffffff"
"echoe part
"endif
call s:MatchColorValue(b:color_pattern[part], part)
"echoe color
"echoe b:color_pattern[color]
"let group = 'cssColor' . tolower(strpart(b:color_pattern[part]["color"], 1))
""exe 'syn match' group '/'.escape(pattern, '/').'/ contained'
"exe 'syn cluster cssColors add='.group
"exe 'hi' group s:color_prefix.'bg='.b:color_pattern[part]["bg"] s:color_prefix.'fg='.b:color_pattern[part]["fg"]
"if !exists('b:matchescache')
"let b:matchescache={}
"endif
"let b:matchescache[part] = matchadd(group, part, -1)
endfor
endfunction
function! s:MatchColorValue(color, part)
if ! len(a:color) | return | endif
let group = 'cssColor' . tolower(a:color)
if !exists('b:color_pattern[a:part]')
exe s:fg_color_calc
exe 'syn cluster cssColors add='.group
exe 'hi' group s:color_prefix.'bg='.color s:color_prefix.'fg='.s:FGForBG(a:color)
let b:color_pattern[a:part] = a:color
endif
if !exists('b:matchescache')
let b:matchescache = {}
elseif !exists('b:matchescache[a:part]')
let b:matchescache[a:part] = matchadd(group, a:part, -1)
endif
"call add(w:matchescache, matchadd(group, a:part, -1))
return ''
endfunction
function! s:HexForRGBValue(r,g,b)
" Convert 80% -> 204, 100% -> 255, etc.
let rgb = map( [a:r,a:g,a:b], 'v:val =~ "%$" ? ( 255 * v:val ) / 100 : v:val' )
return printf( '%02x%02x%02x', rgb[0], rgb[1], rgb[2] )
endfunction
function! s:HexForHSLValue(h,s,l)
" Convert 80% -> 0.8, 100% -> 1.0, etc.
let [s,l] = map( [a:s, a:l], 'v:val =~ "%$" ? v:val / 100.0 : str2float(v:val)' )
" algorithm transcoded to vim from http://www.w3.org/TR/css3-color/#hsl-color
let hh = ( a:h % 360 ) / 360.0
let m2 = l <= 0.5 ? l * ( s + 1 ) : l + s - l * s
let m1 = l * 2 - m2
let rgb = []
for h in [ hh + (1/3.0), hh, hh - (1/3.0) ]
let h = h < 0 ? h + 1 : h > 1 ? h - 1 : h
let v =
\ h * 6 < 1 ? m1 + ( m2 - m1 ) * h * 6 :
\ h * 2 < 1 ? m2 :
\ h * 3 < 2 ? m1 + ( m2 - m1 ) * ( 2/3.0 - h ) * 6 :
\ m1
if v > 1.0 | return '' | endif
let rgb += [ float2nr( 255 * v ) ]
endfor
return printf( '%02x%02x%02x', rgb[0], rgb[1], rgb[2] )
endfunction
function! s:ClearMatches()
call clearmatches()
if !exists('b:matchescache')
return
endif
"for i in values(b:matchescache)
"call matchdelete(i)
"endfor
unlet b:matchescache
endfunction
function! s:VimCssInit(update)
if a:update==1
call s:ClearMatches()
endif
:set isk+=-
:set isk+=#
:set isk+=.
if len(keys(b:color_pattern))>0
call s:RestoreColors()
return
endif
"let b:matchescache = {}
call s:AdditionalColors()
"for i in range(1, line("$"))
call s:PreviewCSSColor(join(getline(1,'$'), "\n"))
"endfor
endfunction
function! s:AdditionalColors()
"if exists('&b:colorDictRegExp')&&b:colorDictRegExp!=''
"return
"endif
" w3c Colors
" plus extra colors
let w:colorDict = {
\'black': '#000000',
\'red': '#ff0000',
\'silver': '#c0c0c0',
\'gray': '#808080',
\'white': '#ffffff',
\'maroon': '#800000',
\'purple': '#800080',
\'fuchsia': '#ff00ff',
\'green': '#008000',
\'lime': '#00ff00',
\'olive': '#808000',
\'yellow': '#ffff00',
\'navy': '#000080',
\'blue': '#0000ff',
\'teal': '#008080',
\'aqua': '#00ffff',
\'aliceblue': '#f0f8ff',
\'antiquewhite': '#faebd7',
\'aquamarine': '#7fffd4',
\'azure': '#f0ffff',
\'beige': '#f5f5dc',
\'bisque': '#ffe4c4',
\'blanchedalmond': '#ffebcd',
\'blueviolet': '#8a2be2',
\'brown': '#a52a2a',
\'burlywood': '#deb887',
\'cadetblue': '#5f9ea0',
\'chartreuse': '#7fff00',
\'chocolate': '#d2691e',
\'coral': '#ff7f50',
\'cornflowerblue': '#6495ed',
\'cornsilk': '#fff8dc',
\'crimson': '#dc143c',
\'cyan': '#00ffff',
\'darkblue': '#00008b',
\'darkcyan': '#008b8b',
\'darkgoldenrod': '#b8860b',
\'darkgray': '#a9a9a9',
\'darkgreen': '#006400',
\'darkgrey': '#a9a9a9',
\'darkkhaki': '#bdb76b',
\'darkmagenta': '#8b008b',
\'darkolivegreen': '#556b2f',
\'darkorchid': '#9932cc',
\'darkred': '#8b0000',
\'darksalmon': '#e9967a',
\'darkseagreen': '#8fbc8f',
\'darkslateblue': '#483d8b',
\'darkslategray': '#2f4f4f',
\'darkslategrey': '#2f4f4f',
\'darkturquoise': '#00ced1',
\'darkviolet': '#9400d3',
\'darkorange': '#ff8c00',
\'deeppink': '#ff1493',
\'deepskyblue': '#00bfff',
\'dimgray': '#696969',
\'dimgrey': '#696969',
\'dodgerblue': '#1e90ff',
\'firebrick': '#b22222',
\'floralwhite': '#fffaf0',
\'forestgreen': '#228b22',
\'gainsboro': '#dcdcdc',
\'ghostwhite': '#f8f8ff',
\'gold': '#ffd700',
\'goldenrod': '#daa520',
\'greenyellow': '#adff2f',
\'grey': '#808080',
\'honeydew': '#f0fff0',
\'hotpink': '#ff69b4',
\'indianred': '#cd5c5c',
\'indigo': '#4b0082',
\'ivory': '#fffff0',
\'khaki': '#f0e68c',
\'lavender': '#e6e6fa',
\'lavenderblush': '#fff0f5',
\'lawngreen': '#7cfc00',
\'lemonchiffon': '#fffacd',
\'lightblue': '#add8e6',
\'lightcoral': '#f08080',
\'lightcyan': '#e0ffff',
\'lightgoldenrodyellow': '#fafad2',
\'lightgray': '#d3d3d3',
\'lightgreen': '#90ee90',
\'lightgrey': '#d3d3d3',
\'lightpink': '#ffb6c1',
\'lightsalmon': '#ffa07a',
\'lightseagreen': '#20b2aa',
\'lightskyblue': '#87cefa',
\'lightslategray': '#778899',
\'lightslategrey': '#778899',
\'lightsteelblue': '#b0c4de',
\'lightyellow': '#ffffe0',
\'limegreen': '#32cd32',
\'linen': '#faf0e6',
\'magenta': '#ff00ff',
\'mediumaquamarine': '#66cdaa',
\'mediumblue': '#0000cd',
\'mediumorchid': '#ba55d3',
\'mediumpurple': '#9370d8',
\'mediumseagreen': '#3cb371',
\'mediumslateblue': '#7b68ee',
\'mediumspringgreen': '#00fa9a',
\'mediumturquoise': '#48d1cc',
\'mediumvioletred': '#c71585',
\'midnightblue': '#191970',
\'mintcream': '#f5fffa',
\'mistyrose': '#ffe4e1',
\'moccasin': '#ffe4b5',
\'navajowhite': '#ffdead',
\'oldlace': '#fdf5e6',
\'olivedrab': '#6b8e23',
\'orange': '#ffa500',
\'orangered': '#ff4500',
\'orchid': '#da70d6',
\'palegoldenrod': '#eee8aa',
\'palegreen': '#98fb98',
\'paleturquoise': '#afeeee',
\'palevioletred': '#d87093',
\'papayawhip': '#ffefd5',
\'peachpuff': '#ffdab9',
\'peru': '#cd853f',
\'pink': '#ffc0cb',
\'plum': '#dda0dd',
\'powderblue': '#b0e0e6',
\'rosybrown': '#bc8f8f',
\'royalblue': '#4169e1',
\'saddlebrown': '#8b4513',
\'salmon': '#fa8072',
\'sandybrown': '#f4a460',
\'seagreen': '#2e8b57',
\'seashell': '#fff5ee',
\'sienna': '#a0522d',
\'skyblue': '#87ceeb',
\'slateblue': '#6a5acd',
\'slategray': '#708090',
\'slategrey': '#708090',
\'snow': '#fffafa',
\'springgreen': '#00ff7f',
\'steelblue': '#4682b4',
\'tan': '#d2b48c',
\'thistle': '#d8bfd8',
\'tomato': '#ff6347',
\'turquoise': '#40e0d0',
\'violet': '#ee82ee',
\'wheat': '#f5deb3',
\'whitesmoke': '#f5f5f5',
\'yellowgreen': '#9acd32'
\}
"let w:colorDictRegExp = '\('
for _color in keys(w:colorDict)
"let w:colorDictRegExp.='\<'._color.'\>\|'
call s:MatchColorValue(strpart(w:colorDict[tolower(_color)], 1), '\<\c'._color.'\>')
endfor
"let w:colorDictRegExp=strpart(w:colorDictRegExp, 0, len(w:colorDictRegExp)-2).'\)\c'
endfunction
function! s:ProcessByLine(w)
call s:PreviewCSSColor(getline(a:w))
endfunction
function! s:PreviewCSSColor(str)
"if !exists('&w:colorDictRegExp')
"endif
let line=a:str "getline(a:w)
let colorexps = {
\ 'hex' : '#[0-9A-Fa-f]\{3\}\>\|#[0-9A-Fa-f]\{6\}\>',
\ 'rgba' : 'rgba\?(\s*\(\d\{1,3}%\?\)\s*,\s*\(\d\{1,3}%\?\)\s*,\s*\(\d\{1,3}%\?\)\s*\%(,[^)]*\)\?)',
\ 'hsla' : 'hsla\?(\s*\(\d\{1,3}%\?\)\s*,\s*\(\d\{1,3}%\?\)\s*,\s*\(\d\{1,3}%\?\)\s*\%(,[^)]*\)\?)'
\ }
"\ 'color': w:colorDictRegExp
"let foundcolor=''
for exp in keys(colorexps)
let place=0
if exists("foundcolor")
unlet foundcolor
endif
while 1
if exp=='rgba'||exp=='hsla'
let foundcolor = matchlist(a:str, colorexps[exp], place)
else
let foundcolor = matchstr(a:str, colorexps[exp], place)
endif
let place = matchend(a:str, colorexps[exp], place)
if empty(foundcolor)
break
endif
if exp=='hex'
let part = foundcolor.'\>'
else
let part = foundcolor[0]
endif
if exp=='hex'
if len(foundcolor) == 4
let foundcolor = substitute(foundcolor, '[[:xdigit:]]', '&&', 'g')
endif
call s:MatchColorValue(strpart(foundcolor, 1), part)
elseif exp=='rgba'
"TODO get rid of duplicated variables
call s:MatchColorValue(s:HexForRGBValue(foundcolor[1], foundcolor[2], foundcolor[3]), part)
elseif exp=='hsla'
call s:MatchColorValue(s:HexForHSLValue(foundcolor[1], foundcolor[2], foundcolor[3]), part)
endif
endwhile
endfor
endfunction
if has("gui_running") || &t_Co==256
" HACK modify cssDefinition to add @cssColors to its contains
redir => cssdef
silent! syn list cssDefinition
redir END
if len( cssdef )
for out in split( cssdef, "\n" )
if out !~ '^cssDefinition ' | continue | endif
let out = substitute( out, ' \+xxx \+', ' ', '' )
let out = substitute( out, ' contains=\zs', '@cssColors,', '' )
exe 'syn region' out
endfor
endif
if ! has('gui_running')
let s:black = 0
let s:white = 15
let s:color_prefix = 'cterm'
let s:fg_color_calc = 'let color = s:XTermColorForRGB(a:color)'
" preset 16 vt100 colors
let s:xtermcolor = [
\ [ 0x00, 0x00, 0x00, 0 ],
\ [ 0xCD, 0x00, 0x00, 1 ],
\ [ 0x00, 0xCD, 0x00, 2 ],
\ [ 0xCD, 0xCD, 0x00, 3 ],
\ [ 0x00, 0x00, 0xEE, 4 ],
\ [ 0xCD, 0x00, 0xCD, 5 ],
\ [ 0x00, 0xCD, 0xCD, 6 ],
\ [ 0xE5, 0xE5, 0xE5, 7 ],
\ [ 0x7F, 0x7F, 0x7F, 8 ],
\ [ 0xFF, 0x00, 0x00, 9 ],
\ [ 0x00, 0xFF, 0x00, 10 ],
\ [ 0xFF, 0xFF, 0x00, 11 ],
\ [ 0x5C, 0x5C, 0xFF, 12 ],
\ [ 0xFF, 0x00, 0xFF, 13 ],
\ [ 0x00, 0xFF, 0xFF, 14 ],
\ [ 0xFF, 0xFF, 0xFF, 15 ]]
" grayscale ramp
" (value is 8+10*lum for lum in 0..23)
let s:xtermcolor += [
\ [ 0x08, 0x08, 0x08, 232 ],
\ [ 0x12, 0x12, 0x12, 233 ],
\ [ 0x1C, 0x1C, 0x1C, 234 ],
\ [ 0x26, 0x26, 0x26, 235 ],
\ [ 0x30, 0x30, 0x30, 236 ],
\ [ 0x3A, 0x3A, 0x3A, 237 ],
\ [ 0x44, 0x44, 0x44, 238 ],
\ [ 0x4E, 0x4E, 0x4E, 239 ],
\ [ 0x58, 0x58, 0x58, 240 ],
\ [ 0x62, 0x62, 0x62, 241 ],
\ [ 0x6C, 0x6C, 0x6C, 242 ],
\ [ 0x76, 0x76, 0x76, 243 ],
\ [ 0x80, 0x80, 0x80, 244 ],
\ [ 0x8A, 0x8A, 0x8A, 245 ],
\ [ 0x94, 0x94, 0x94, 246 ],
\ [ 0x9E, 0x9E, 0x9E, 247 ],
\ [ 0xA8, 0xA8, 0xA8, 248 ],
\ [ 0xB2, 0xB2, 0xB2, 249 ],
\ [ 0xBC, 0xBC, 0xBC, 250 ],
\ [ 0xC6, 0xC6, 0xC6, 251 ],
\ [ 0xD0, 0xD0, 0xD0, 252 ],
\ [ 0xDA, 0xDA, 0xDA, 253 ],
\ [ 0xE4, 0xE4, 0xE4, 254 ],
\ [ 0xEE, 0xEE, 0xEE, 255 ]]
" the 6 values used in the xterm color cube
" 0 95 135 175 215 255
let s:cubergb = [ 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF ]
" 0..255 mapped to 0..5 based on the color cube values
let s:xvquant = repeat([0],48)
\ + repeat([1],68)
\ + repeat([2],40)
\ + repeat([3],40)
\ + repeat([4],40)
\ + repeat([5],20)
" tweak the mapping for the exact matches (0 and 1 already correct)
let s:xvquant[s:cubergb[2]] = 2
let s:xvquant[s:cubergb[3]] = 3
let s:xvquant[s:cubergb[4]] = 4
let s:xvquant[s:cubergb[5]] = 5
" selects the nearest xterm color for a rgb value like #FF0000
function! s:XTermColorForRGB(color)
let best_match=0
let smallest_distance = 10000000000
let color = tolower(a:color)
let r = s:hex[color[0:1]]
let g = s:hex[color[2:3]]
let b = s:hex[color[4:5]]
let vr = s:xvquant[r]
let vg = s:xvquant[g]
let vb = s:xvquant[b]
let cidx = vr * 36 + vg * 6 + vb + 16
let ccol = [ s:cubergb[vr], s:cubergb[vg], s:cubergb[vb], cidx ]
for [tr,tg,tb,idx] in [ ccol ] + s:xtermcolor
let dr = tr - r
let dg = tg - g
let db = tb - b
let distance = dr*dr + dg*dg + db*db
if distance == 0 | return idx | endif
if distance > smallest_distance | continue | endif
let smallest_distance = distance
let best_match = idx
endfor
return best_match
endfunction
endif
hi cssColor000000 guibg=#000000 guifg=#FFFFFF ctermbg=16 ctermfg=231 | syn cluster cssColors add=cssColor000000
hi cssColor000080 guibg=#000080 guifg=#FFFFFF ctermbg=235 ctermfg=231 | syn cluster cssColors add=cssColor000080
hi cssColor00008b guibg=#00008B guifg=#FFFFFF ctermbg=4 ctermfg=231 | syn cluster cssColors add=cssColor00008b
hi cssColor0000cd guibg=#0000CD guifg=#FFFFFF ctermbg=4 ctermfg=231 | syn cluster cssColors add=cssColor0000cd
hi cssColor0000ff guibg=#0000FF guifg=#FFFFFF ctermbg=4 ctermfg=231 | syn cluster cssColors add=cssColor0000ff
hi cssColor006400 guibg=#006400 guifg=#FFFFFF ctermbg=235 ctermfg=231 | syn cluster cssColors add=cssColor006400
hi cssColor008000 guibg=#008000 guifg=#FFFFFF ctermbg=2 ctermfg=231 | syn cluster cssColors add=cssColor008000
hi cssColor008080 guibg=#008080 guifg=#FFFFFF ctermbg=30 ctermfg=231 | syn cluster cssColors add=cssColor008080
hi cssColor008b8b guibg=#008B8B guifg=#FFFFFF ctermbg=30 ctermfg=231 | syn cluster cssColors add=cssColor008b8b
hi cssColor00bfff guibg=#00BFFF guifg=#000000 ctermbg=6 ctermfg=16 | syn cluster cssColors add=cssColor00bfff
hi cssColor00ced1 guibg=#00CED1 guifg=#000000 ctermbg=6 ctermfg=16 | syn cluster cssColors add=cssColor00ced1
hi cssColor00fa9a guibg=#00FA9A guifg=#000000 ctermbg=6 ctermfg=16 | syn cluster cssColors add=cssColor00fa9a
hi cssColor00ff00 guibg=#00FF00 guifg=#000000 ctermbg=10 ctermfg=16 | syn cluster cssColors add=cssColor00ff00
hi cssColor00ff7f guibg=#00FF7F guifg=#000000 ctermbg=6 ctermfg=16 | syn cluster cssColors add=cssColor00ff7f
hi cssColor00ffff guibg=#00FFFF guifg=#000000 ctermbg=51 ctermfg=16 | syn cluster cssColors add=cssColor00ffff
hi cssColor191970 guibg=#191970 guifg=#FFFFFF ctermbg=237 ctermfg=231 | syn cluster cssColors add=cssColor191970
hi cssColor1e90ff guibg=#1E90FF guifg=#000000 ctermbg=12 ctermfg=16 | syn cluster cssColors add=cssColor1e90ff
hi cssColor20b2aa guibg=#20B2AA guifg=#000000 ctermbg=37 ctermfg=16 | syn cluster cssColors add=cssColor20b2aa
hi cssColor228b22 guibg=#228B22 guifg=#FFFFFF ctermbg=2 ctermfg=231 | syn cluster cssColors add=cssColor228b22
hi cssColor2e8b57 guibg=#2E8B57 guifg=#FFFFFF ctermbg=240 ctermfg=231 | syn cluster cssColors add=cssColor2e8b57
hi cssColor2f4f4f guibg=#2F4F4F guifg=#FFFFFF ctermbg=238 ctermfg=231 | syn cluster cssColors add=cssColor2f4f4f
hi cssColor32cd32 guibg=#32CD32 guifg=#000000 ctermbg=2 ctermfg=16 | syn cluster cssColors add=cssColor32cd32
hi cssColor3cb371 guibg=#3CB371 guifg=#000000 ctermbg=71 ctermfg=16 | syn cluster cssColors add=cssColor3cb371
hi cssColor40e0d0 guibg=#40E0D0 guifg=#000000 ctermbg=80 ctermfg=16 | syn cluster cssColors add=cssColor40e0d0
hi cssColor4169e1 guibg=#4169E1 guifg=#FFFFFF ctermbg=12 ctermfg=231 | syn cluster cssColors add=cssColor4169e1
hi cssColor4682b4 guibg=#4682B4 guifg=#FFFFFF ctermbg=67 ctermfg=231 | syn cluster cssColors add=cssColor4682b4
hi cssColor483d8b guibg=#483D8B guifg=#FFFFFF ctermbg=240 ctermfg=231 | syn cluster cssColors add=cssColor483d8b
hi cssColor48d1cc guibg=#48D1CC guifg=#000000 ctermbg=80 ctermfg=16 | syn cluster cssColors add=cssColor48d1cc
hi cssColor4b0082 guibg=#4B0082 guifg=#FFFFFF ctermbg=238 ctermfg=231 | syn cluster cssColors add=cssColor4b0082
hi cssColor556b2f guibg=#556B2F guifg=#FFFFFF ctermbg=239 ctermfg=231 | syn cluster cssColors add=cssColor556b2f
hi cssColor5f9ea0 guibg=#5F9EA0 guifg=#000000 ctermbg=73 ctermfg=16 | syn cluster cssColors add=cssColor5f9ea0
hi cssColor6495ed guibg=#6495ED guifg=#000000 ctermbg=12 ctermfg=16 | syn cluster cssColors add=cssColor6495ed
hi cssColor66cdaa guibg=#66CDAA guifg=#000000 ctermbg=79 ctermfg=16 | syn cluster cssColors add=cssColor66cdaa
hi cssColor696969 guibg=#696969 guifg=#FFFFFF ctermbg=242 ctermfg=231 | syn cluster cssColors add=cssColor696969
hi cssColor6a5acd guibg=#6A5ACD guifg=#FFFFFF ctermbg=12 ctermfg=231 | syn cluster cssColors add=cssColor6a5acd
hi cssColor6b8e23 guibg=#6B8E23 guifg=#FFFFFF ctermbg=241 ctermfg=231 | syn cluster cssColors add=cssColor6b8e23
hi cssColor708090 guibg=#708090 guifg=#000000 ctermbg=66 ctermfg=16 | syn cluster cssColors add=cssColor708090
hi cssColor778899 guibg=#778899 guifg=#000000 ctermbg=102 ctermfg=16 | syn cluster cssColors add=cssColor778899
hi cssColor7b68ee guibg=#7B68EE guifg=#000000 ctermbg=12 ctermfg=16 | syn cluster cssColors add=cssColor7b68ee
hi cssColor7cfc00 guibg=#7CFC00 guifg=#000000 ctermbg=3 ctermfg=16 | syn cluster cssColors add=cssColor7cfc00
hi cssColor7fff00 guibg=#7FFF00 guifg=#000000 ctermbg=3 ctermfg=16 | syn cluster cssColors add=cssColor7fff00
hi cssColor7fffd4 guibg=#7FFFD4 guifg=#000000 ctermbg=122 ctermfg=16 | syn cluster cssColors add=cssColor7fffd4
hi cssColor800000 guibg=#800000 guifg=#FFFFFF ctermbg=88 ctermfg=231 | syn cluster cssColors add=cssColor800000
hi cssColor800080 guibg=#800080 guifg=#FFFFFF ctermbg=240 ctermfg=231 | syn cluster cssColors add=cssColor800080
hi cssColor808000 guibg=#808000 guifg=#FFFFFF ctermbg=240 ctermfg=231 | syn cluster cssColors add=cssColor808000
hi cssColor808080 guibg=#808080 guifg=#000000 ctermbg=244 ctermfg=16 | syn cluster cssColors add=cssColor808080
hi cssColor87ceeb guibg=#87CEEB guifg=#000000 ctermbg=117 ctermfg=16 | syn cluster cssColors add=cssColor87ceeb
hi cssColor87cefa guibg=#87CEFA guifg=#000000 ctermbg=117 ctermfg=16 | syn cluster cssColors add=cssColor87cefa
hi cssColor8a2be2 guibg=#8A2BE2 guifg=#FFFFFF ctermbg=12 ctermfg=231 | syn cluster cssColors add=cssColor8a2be2
hi cssColor8b0000 guibg=#8B0000 guifg=#FFFFFF ctermbg=88 ctermfg=231 | syn cluster cssColors add=cssColor8b0000
hi cssColor8b008b guibg=#8B008B guifg=#FFFFFF ctermbg=5 ctermfg=231 | syn cluster cssColors add=cssColor8b008b
hi cssColor8b4513 guibg=#8B4513 guifg=#FFFFFF ctermbg=94 ctermfg=231 | syn cluster cssColors add=cssColor8b4513
hi cssColor8fbc8f guibg=#8FBC8F guifg=#000000 ctermbg=108 ctermfg=16 | syn cluster cssColors add=cssColor8fbc8f
hi cssColor90ee90 guibg=#90EE90 guifg=#000000 ctermbg=249 ctermfg=16 | syn cluster cssColors add=cssColor90ee90
hi cssColor9370d8 guibg=#9370D8 guifg=#000000 ctermbg=12 ctermfg=16 | syn cluster cssColors add=cssColor9370d8
hi cssColor9400d3 guibg=#9400D3 guifg=#FFFFFF ctermbg=5 ctermfg=231 | syn cluster cssColors add=cssColor9400d3
hi cssColor98fb98 guibg=#98FB98 guifg=#000000 ctermbg=250 ctermfg=16 | syn cluster cssColors add=cssColor98fb98
hi cssColor9932cc guibg=#9932CC guifg=#FFFFFF ctermbg=5 ctermfg=231 | syn cluster cssColors add=cssColor9932cc
hi cssColor9acd32 guibg=#9ACD32 guifg=#000000 ctermbg=3 ctermfg=16 | syn cluster cssColors add=cssColor9acd32
hi cssColora0522d guibg=#A0522D guifg=#FFFFFF ctermbg=130 ctermfg=231 | syn cluster cssColors add=cssColora0522d
hi cssColora52a2a guibg=#A52A2A guifg=#FFFFFF ctermbg=124 ctermfg=231 | syn cluster cssColors add=cssColora52a2a
hi cssColora9a9a9 guibg=#A9A9A9 guifg=#000000 ctermbg=248 ctermfg=16 | syn cluster cssColors add=cssColora9a9a9
hi cssColoradd8e6 guibg=#ADD8E6 guifg=#000000 ctermbg=152 ctermfg=16 | syn cluster cssColors add=cssColoradd8e6
hi cssColoradff2f guibg=#ADFF2F guifg=#000000 ctermbg=3 ctermfg=16 | syn cluster cssColors add=cssColoradff2f
hi cssColorafeeee guibg=#AFEEEE guifg=#000000 ctermbg=159 ctermfg=16 | syn cluster cssColors add=cssColorafeeee
hi cssColorb0c4de guibg=#B0C4DE guifg=#000000 ctermbg=152 ctermfg=16 | syn cluster cssColors add=cssColorb0c4de
hi cssColorb0e0e6 guibg=#B0E0E6 guifg=#000000 ctermbg=152 ctermfg=16 | syn cluster cssColors add=cssColorb0e0e6
hi cssColorb22222 guibg=#B22222 guifg=#FFFFFF ctermbg=124 ctermfg=231 | syn cluster cssColors add=cssColorb22222
hi cssColorb8860b guibg=#B8860B guifg=#000000 ctermbg=3 ctermfg=16 | syn cluster cssColors add=cssColorb8860b
hi cssColorba55d3 guibg=#BA55D3 guifg=#000000 ctermbg=5 ctermfg=16 | syn cluster cssColors add=cssColorba55d3
hi cssColorbc8f8f guibg=#BC8F8F guifg=#000000 ctermbg=138 ctermfg=16 | syn cluster cssColors add=cssColorbc8f8f
hi cssColorbdb76b guibg=#BDB76B guifg=#000000 ctermbg=247 ctermfg=16 | syn cluster cssColors add=cssColorbdb76b
hi cssColorc0c0c0 guibg=#C0C0C0 guifg=#000000 ctermbg=250 ctermfg=16 | syn cluster cssColors add=cssColorc0c0c0
hi cssColorc71585 guibg=#C71585 guifg=#FFFFFF ctermbg=5 ctermfg=231 | syn cluster cssColors add=cssColorc71585
hi cssColorcd5c5c guibg=#CD5C5C guifg=#000000 ctermbg=167 ctermfg=16 | syn cluster cssColors add=cssColorcd5c5c
hi cssColorcd853f guibg=#CD853F guifg=#000000 ctermbg=173 ctermfg=16 | syn cluster cssColors add=cssColorcd853f
hi cssColord2691e guibg=#D2691E guifg=#000000 ctermbg=166 ctermfg=16 | syn cluster cssColors add=cssColord2691e
hi cssColord2b48c guibg=#D2B48C guifg=#000000 ctermbg=180 ctermfg=16 | syn cluster cssColors add=cssColord2b48c
hi cssColord3d3d3 guibg=#D3D3D3 guifg=#000000 ctermbg=252 ctermfg=16 | syn cluster cssColors add=cssColord3d3d3
hi cssColord87093 guibg=#D87093 guifg=#000000 ctermbg=168 ctermfg=16 | syn cluster cssColors add=cssColord87093
hi cssColord8bfd8 guibg=#D8BFD8 guifg=#000000 ctermbg=252 ctermfg=16 | syn cluster cssColors add=cssColord8bfd8
hi cssColorda70d6 guibg=#DA70D6 guifg=#000000 ctermbg=249 ctermfg=16 | syn cluster cssColors add=cssColorda70d6
hi cssColordaa520 guibg=#DAA520 guifg=#000000 ctermbg=3 ctermfg=16 | syn cluster cssColors add=cssColordaa520
hi cssColordc143c guibg=#DC143C guifg=#FFFFFF ctermbg=161 ctermfg=231 | syn cluster cssColors add=cssColordc143c
hi cssColordcdcdc guibg=#DCDCDC guifg=#000000 ctermbg=253 ctermfg=16 | syn cluster cssColors add=cssColordcdcdc
hi cssColordda0dd guibg=#DDA0DD guifg=#000000 ctermbg=182 ctermfg=16 | syn cluster cssColors add=cssColordda0dd
hi cssColordeb887 guibg=#DEB887 guifg=#000000 ctermbg=180 ctermfg=16 | syn cluster cssColors add=cssColordeb887
hi cssColore0ffff guibg=#E0FFFF guifg=#000000 ctermbg=195 ctermfg=16 | syn cluster cssColors add=cssColore0ffff
hi cssColore6e6fa guibg=#E6E6FA guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColore6e6fa
hi cssColore9967a guibg=#E9967A guifg=#000000 ctermbg=174 ctermfg=16 | syn cluster cssColors add=cssColore9967a
hi cssColoree82ee guibg=#EE82EE guifg=#000000 ctermbg=251 ctermfg=16 | syn cluster cssColors add=cssColoree82ee
hi cssColoreee8aa guibg=#EEE8AA guifg=#000000 ctermbg=223 ctermfg=16 | syn cluster cssColors add=cssColoreee8aa
hi cssColorf08080 guibg=#F08080 guifg=#000000 ctermbg=210 ctermfg=16 | syn cluster cssColors add=cssColorf08080
hi cssColorf0e68c guibg=#F0E68C guifg=#000000 ctermbg=222 ctermfg=16 | syn cluster cssColors add=cssColorf0e68c
hi cssColorf0f8ff guibg=#F0F8FF guifg=#000000 ctermbg=15 ctermfg=16 | syn cluster cssColors add=cssColorf0f8ff
hi cssColorf0fff0 guibg=#F0FFF0 guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorf0fff0
hi cssColorf0ffff guibg=#F0FFFF guifg=#000000 ctermbg=15 ctermfg=16 | syn cluster cssColors add=cssColorf0ffff
hi cssColorf4a460 guibg=#F4A460 guifg=#000000 ctermbg=215 ctermfg=16 | syn cluster cssColors add=cssColorf4a460
hi cssColorf5deb3 guibg=#F5DEB3 guifg=#000000 ctermbg=223 ctermfg=16 | syn cluster cssColors add=cssColorf5deb3
hi cssColorf5f5dc guibg=#F5F5DC guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorf5f5dc
hi cssColorf5f5f5 guibg=#F5F5F5 guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorf5f5f5
hi cssColorf5fffa guibg=#F5FFFA guifg=#000000 ctermbg=15 ctermfg=16 | syn cluster cssColors add=cssColorf5fffa
hi cssColorf8f8ff guibg=#F8F8FF guifg=#000000 ctermbg=15 ctermfg=16 | syn cluster cssColors add=cssColorf8f8ff
hi cssColorfa8072 guibg=#FA8072 guifg=#000000 ctermbg=209 ctermfg=16 | syn cluster cssColors add=cssColorfa8072
hi cssColorfaebd7 guibg=#FAEBD7 guifg=#000000 ctermbg=7 ctermfg=16 | syn cluster cssColors add=cssColorfaebd7
hi cssColorfaf0e6 guibg=#FAF0E6 guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorfaf0e6
hi cssColorfafad2 guibg=#FAFAD2 guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorfafad2
hi cssColorfdf5e6 guibg=#FDF5E6 guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorfdf5e6
hi cssColorff0000 guibg=#FF0000 guifg=#FFFFFF ctermbg=196 ctermfg=231 | syn cluster cssColors add=cssColorff0000
hi cssColorff00ff guibg=#FF00FF guifg=#FFFFFF ctermbg=13 ctermfg=231 | syn cluster cssColors add=cssColorff00ff
hi cssColorff1493 guibg=#FF1493 guifg=#FFFFFF ctermbg=5 ctermfg=231 | syn cluster cssColors add=cssColorff1493
hi cssColorff4500 guibg=#FF4500 guifg=#FFFFFF ctermbg=9 ctermfg=231 | syn cluster cssColors add=cssColorff4500
hi cssColorff6347 guibg=#FF6347 guifg=#000000 ctermbg=203 ctermfg=16 | syn cluster cssColors add=cssColorff6347
hi cssColorff69b4 guibg=#FF69B4 guifg=#000000 ctermbg=205 ctermfg=16 | syn cluster cssColors add=cssColorff69b4
hi cssColorff7f50 guibg=#FF7F50 guifg=#000000 ctermbg=209 ctermfg=16 | syn cluster cssColors add=cssColorff7f50
hi cssColorff8c00 guibg=#FF8C00 guifg=#000000 ctermbg=3 ctermfg=16 | syn cluster cssColors add=cssColorff8c00
hi cssColorffa07a guibg=#FFA07A guifg=#000000 ctermbg=216 ctermfg=16 | syn cluster cssColors add=cssColorffa07a
hi cssColorffa500 guibg=#FFA500 guifg=#000000 ctermbg=3 ctermfg=16 | syn cluster cssColors add=cssColorffa500
hi cssColorffb6c1 guibg=#FFB6C1 guifg=#000000 ctermbg=217 ctermfg=16 | syn cluster cssColors add=cssColorffb6c1
hi cssColorffc0cb guibg=#FFC0CB guifg=#000000 ctermbg=218 ctermfg=16 | syn cluster cssColors add=cssColorffc0cb
hi cssColorffd700 guibg=#FFD700 guifg=#000000 ctermbg=11 ctermfg=16 | syn cluster cssColors add=cssColorffd700
hi cssColorffdab9 guibg=#FFDAB9 guifg=#000000 ctermbg=223 ctermfg=16 | syn cluster cssColors add=cssColorffdab9
hi cssColorffdead guibg=#FFDEAD guifg=#000000 ctermbg=223 ctermfg=16 | syn cluster cssColors add=cssColorffdead
hi cssColorffe4b5 guibg=#FFE4B5 guifg=#000000 ctermbg=223 ctermfg=16 | syn cluster cssColors add=cssColorffe4b5
hi cssColorffe4c4 guibg=#FFE4C4 guifg=#000000 ctermbg=224 ctermfg=16 | syn cluster cssColors add=cssColorffe4c4
hi cssColorffe4e1 guibg=#FFE4E1 guifg=#000000 ctermbg=224 ctermfg=16 | syn cluster cssColors add=cssColorffe4e1
hi cssColorffebcd guibg=#FFEBCD guifg=#000000 ctermbg=7 ctermfg=16 | syn cluster cssColors add=cssColorffebcd
hi cssColorffefd5 guibg=#FFEFD5 guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorffefd5
hi cssColorfff0f5 guibg=#FFF0F5 guifg=#000000 ctermbg=15 ctermfg=16 | syn cluster cssColors add=cssColorfff0f5
hi cssColorfff5ee guibg=#FFF5EE guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorfff5ee
hi cssColorfff8dc guibg=#FFF8DC guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorfff8dc
hi cssColorfffacd guibg=#FFFACD guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorfffacd
hi cssColorfffaf0 guibg=#FFFAF0 guifg=#000000 ctermbg=15 ctermfg=16 | syn cluster cssColors add=cssColorfffaf0
hi cssColorfffafa guibg=#FFFAFA guifg=#000000 ctermbg=15 ctermfg=16 | syn cluster cssColors add=cssColorfffafa
hi cssColorffff00 guibg=#FFFF00 guifg=#000000 ctermbg=11 ctermfg=16 | syn cluster cssColors add=cssColorffff00
hi cssColorffffe0 guibg=#FFFFE0 guifg=#000000 ctermbg=255 ctermfg=16 | syn cluster cssColors add=cssColorffffe0
hi cssColorfffff0 guibg=#FFFFF0 guifg=#000000 ctermbg=15 ctermfg=16 | syn cluster cssColors add=cssColorfffff0
hi cssColorffffff guibg=#FFFFFF guifg=#000000 ctermbg=231 ctermfg=16 | syn cluster cssColors add=cssColorffffff
"call s:VimCssInit(1)
":augroup css
"au!
autocmd CursorMovedI <buffer> silent call s:ProcessByLine('.')
autocmd ColorScheme <buffer> silent call s:VimCssInit(1)
autocmd BufEnter <buffer> silent call s:VimCssInit(1)
":augroup END
"autocmd CursorMoved <buffer> silent call s:ProcessByLine('.')
endif

View File

@@ -9,3 +9,4 @@ syn region coffeeScript start=#<script [^>]*type="text/coffeescript"[^>]*>#
\ end=#</script>#me=s-1 keepend
\ contains=@htmlCoffeeScript,htmlScriptTag,@htmlPreproc
\ containedin=htmlHead
syn include syntax/css/vim-coloresque.vim

1
after/syntax/less.vim Normal file
View File

@@ -0,0 +1 @@
syn include syntax/css/vim-coloresque.vim

32
after/syntax/rspec.vim Normal file
View File

@@ -0,0 +1,32 @@
"
" An rspec syntax file
" Originally from http://www.vim.org/scripts/script.php?script_id=2286
"
"
runtime! syntax/ruby.vim
unlet! b:current_syntax
syntax keyword rspecGroupMethods context describe example it its let it_should_behave_like shared_examples_for subject it_behaves_like pending specify When Then Given Invariant feature scenario given
highlight link rspecGroupMethods Type
syntax keyword rspecBeforeAndAfter after after_suite_parts append_after append_before before before_suite_parts prepend_after prepend_before around
highlight link rspecBeforeAndAfter Statement
syntax keyword rspecMocks double mock stub stub_chain
highlight link rspecMocks Constant
syntax keyword rspecMockMethods and_raise and_return and_throw and_yield build_child called_max_times expected_args invoke matches
highlight link rspecMockMethods Function
syntax keyword rspecKeywords should should_not should_not_receive should_receive
highlight link rspecKeywords Constant
syntax keyword rspecMatchers be change eql equal exist expect have have_at_least have_at_most have_exactly include match matcher raise_error raise_exception respond_to satisfy throw_symbol to to_not not_to when wrap_expectation
syntax match rspecMatchers /\<\(be\|have\)_\w\+\>/
highlight link rspecMatchers Function
syntax keyword rspecMessageExpectation advise any_args any_number_of_times anything at_least at_most exactly expected_messages_received generate_error hash_including hash_not_including ignoring_args instance_of matches_at_least_count matches_at_most_count matches_exact_count matches_name_but_not_args negative_expectation_for never no_args once ordered similar_messages times twice verify_messages_received with
highlight link rspecMessageExpectation Function
let b:current_syntax = 'rspec'

View File

@@ -15,6 +15,6 @@ syn match tomdocDescriptions +\s*Public:+he=e-1 containedin=rubyComment containe
syn match tomdocDescriptions +\s*Internal:+he=e-1 containedin=rubyComment contained
syn match tomdocDescriptions +\s*Deprecated:+he=e-1 containedin=rubyComment contained
hi default link tomdocDescriptions TODO
hi default link tomdocKeywords TODO
hi default link tomdocDescriptions String
hi default link tomdocKeywords String
hi default link tomdocArguments HELP

33
after/syntax/rust.vim Normal file
View File

@@ -0,0 +1,33 @@
if !exists('g:rust_conceal') || !has('conceal') || &enc != 'utf-8'
finish
endif
" For those who don't want to see `::`...
if exists('g:rust_conceal_mod_path')
syn match rustNiceOperator "::" conceal cchar=
endif
syn match rustRightArrowHead contained ">" conceal cchar= 
syn match rustRightArrowTail contained "-" conceal cchar=
syn match rustNiceOperator "->" contains=rustRightArrowHead,rustRightArrowTail
syn match rustFatRightArrowHead contained ">" conceal cchar= 
syn match rustFatRightArrowTail contained "=" conceal cchar=
syn match rustNiceOperator "=>" contains=rustFatRightArrowHead,rustFatRightArrowTail
syn match rustNiceOperator /\<\@!_\(_*\>\)\@=/ conceal cchar=
" For those who don't want to see `pub`...
if exists('g:rust_conceal_pub')
syn match rustPublicSigil contained "pu" conceal cchar=
syn match rustPublicRest contained "b" conceal cchar= 
syn match rustNiceOperator "pub " contains=rustPublicSigil,rustPublicRest
endif
hi link rustNiceOperator Operator
if !exists('g:rust_conceal_mod_path')
hi! link Conceal Operator
endif
setlocal conceallevel=2

1
after/syntax/sass.vim Normal file
View File

@@ -0,0 +1 @@
syn include syntax/css/vim-coloresque.vim

1
after/syntax/scss.vim Normal file
View File

@@ -0,0 +1 @@
syn include syntax/css/vim-coloresque.vim

1
after/syntax/stylus.vim Normal file
View File

@@ -0,0 +1 @@
syn include syntax/css/vim-coloresque.vim

4
after/syntax/tex.vim Normal file
View File

@@ -0,0 +1,4 @@
" adds support for cleverref package
" \Cref, \cref, \cpageref, \labelcref, \labelcpageref
syn region texRefZone matchgroup=texStatement start="\\Cref{" end="}\|%stopzone\>" contains=@texRefGroup
syn region texRefZone matchgroup=texStatement start="\\\(label\|\)c\(page\|\)ref{" end="}\|%stopzone\>" contains=@texRefGroup

1
after/syntax/vim.vim Normal file
View File

@@ -0,0 +1 @@
syn include syntax/css/vim-coloresque.vim

View File

@@ -1,219 +0,0 @@
" Vim omni completion file
" Language: Erlang
" Author: Oscar Hellström <oscar@oscarh.net>
" Contributors: kTT (http://github.com/kTT)
" Ricardo Catalinas Jiménez <jimenezrick@gmail.com>
" Eduardo Lopez (http://github.com/tapichu)
" Zhihui Jiao (http://github.com/onlychoice)
" License: Vim license
" Version: 2012/11/26
if !exists('g:erlang_completion_cache')
let g:erlang_completion_cache = 1
endif
" Completion program path
let s:erlang_complete_file = expand('<sfile>:p:h') . '/erlang_complete.erl'
" Modules cache used to speed up the completion
let s:modules_cache = {}
" File cache for persistence between Vim sessions
if filewritable(expand('<sfile>:p:h')) == 2
let s:file_cache = expand('<sfile>:p:h') . '/vimerl_cache'
else
let s:file_cache = '/tmp/vimerl_cache'
endif
" Patterns for completions
let s:erlang_local_func_beg = '\(\<[0-9A-Za-z_-]*\|\s*\)$'
let s:erlang_external_func_beg = '\<[0-9A-Za-z_-]\+:[0-9A-Za-z_-]*$'
let s:erlang_blank_line = '^\s*\(%.*\)\?$'
" Main function for completion
function erlang_complete#Complete(findstart, base)
let lnum = line('.')
let column = col('.')
let line = strpart(getline('.'), 0, column - 1)
" 1) Check if the char to the left of us are part of a function call
"
" Nothing interesting is written at the char just before the cursor
" This means _anything_ could be started here
" In this case, keyword completion should probably be used,
" for now we'll only try and complete local functions.
"
" TODO: Examine if we can stare Identifiers end complete on them
" Is this worth it? Is /completion/ of a "blank" wanted? Can we consider
" `(' interesting and check if we are in a function call etc.?
if line[column - 2] !~ '[0-9A-Za-z:_-]'
if a:findstart
return column
else
return s:ErlangFindLocalFunc(a:base)
endif
endif
" 2) Function in external module
if line =~ s:erlang_external_func_beg
let delimiter = match(line, ':[0-9A-Za-z_-]*$') + 1
if a:findstart
return delimiter
else
let module = matchstr(line[:-2], '\<\k*\>$')
return s:ErlangFindExternalFunc(module, a:base)
endif
endif
" 3) Local function
if line =~ s:erlang_local_func_beg
let funcstart = match(line, ':\@<![0-9A-Za-z_-]*$')
if a:findstart
return funcstart
else
return s:ErlangFindLocalFunc(a:base)
endif
endif
" 4) Unhandled situation
if a:findstart
return -1
else
return []
endif
endfunction
" Find the next non-blank line
function s:ErlangFindNextNonBlank(lnum)
let lnum = nextnonblank(a:lnum + 1)
let line = getline(lnum)
while line =~ s:erlang_blank_line && 0 != lnum
let lnum = nextnonblank(lnum + 1)
let line = getline(lnum)
endwhile
return lnum
endfunction
" Find external function names
function s:ErlangFindExternalFunc(module, base)
" If the module is cached, load its functions
if has_key(s:modules_cache, a:module)
for field_cache in get(s:modules_cache, a:module)
if match(field_cache.word, a:base) == 0
call complete_add(field_cache)
endif
endfor
return []
endif
let functions = system(s:erlang_complete_file . ' ' . a:module)
for function_spec in split(functions, '\n')
if match(function_spec, a:base) == 0
let function_name = matchstr(function_spec, a:base . '\w*')
let field = {'word': function_name . '(', 'abbr': function_spec,
\ 'kind': 'f', 'dup': 1}
call complete_add(field)
" Populate the cache only when iterating over all the
" module functions (i.e. no prefix for the completion)
if g:erlang_completion_cache && a:base == ''
if !has_key(s:modules_cache, a:module)
let s:modules_cache[a:module] = [field]
else
let fields_cache = get(s:modules_cache, a:module)
let s:modules_cache[a:module] = add(fields_cache, field)
endif
endif
" The user entered some text, so stop the completion
if complete_check()
" The module couldn't be entirely cached
if has_key(s:modules_cache, a:module)
call remove(s:modules_cache, a:module)
endif
break
endif
endif
endfor
call s:ErlangWriteCache(a:module)
return []
endfunction
" Find local function names
function s:ErlangFindLocalFunc(base)
" Begin at line 1
let lnum = s:ErlangFindNextNonBlank(1)
if "" == a:base
let base = '\w' " Used to match against word symbol
else
let base = a:base
endif
while 0 != lnum && !complete_check()
let line = getline(lnum)
let function_name = matchstr(line, '^' . base . '[0-9A-Za-z_-]\+(\@=')
if function_name != ""
call complete_add({'word': function_name, 'kind': 'f'})
endif
let lnum = s:ErlangFindNextNonBlank(lnum)
endwhile
return []
endfunction
function s:ErlangLoadCache()
if filereadable(s:file_cache)
for line in readfile(s:file_cache)
let cache_entry = eval(line)
" cache_entry is a dict with just one key with the
" module name and the function list we are going to
" add to the memory cache as the value of this key
for mod_name in keys(cache_entry)
let func_list = get(cache_entry, mod_name)
let s:modules_cache[mod_name] = func_list
endfor
endfor
endif
endfunction
function s:ErlangWriteCache(module)
" Write all the module functions to the cache file
if has_key(s:modules_cache, a:module)
let func_list = get(s:modules_cache, a:module)
if len(func_list) > 0
let cache_entry = {a:module : func_list}
execute 'redir >>' . s:file_cache
silent echon cache_entry
silent echon "\n"
redir END
endif
endif
endfunction
function s:ErlangPurgeCache(...)
for mod_name in a:000
if has_key(s:modules_cache, mod_name)
call remove(s:modules_cache, mod_name)
endif
endfor
" Delete the old cache file
call delete(s:file_cache)
" Write a new one
for mod_name in keys(s:modules_cache)
call s:ErlangWriteCache(mod_name)
endfor
endfunction
" Load the file cache when this script is autoloaded
call s:ErlangLoadCache()
" Command for removing modules from the cache
command -nargs=+ ErlangPurgeCache silent call s:ErlangPurgeCache(<f-args>)

161
autoload/erlangcomplete.vim Normal file
View File

@@ -0,0 +1,161 @@
" ------------------------------------------------------------------------------
" Vim omni-completion script
" Author: Oscar Hellström
" Email: oscar@oscarh.net
" Version: 2010-08-10
" Contributors: kTT (http://github.com/kTT)
" Ricardo Catalinas Jiménez <jimenezrick@gmail.com>
" ------------------------------------------------------------------------------
" Patterns for completions {{{1
let s:erlangLocalFuncBeg = '\(\<[0-9A-Za-z_-]*\|\s*\)$'
let s:erlangExternalFuncBeg = '\<[0-9A-Za-z_-]\+:[0-9A-Za-z_-]*$'
let s:ErlangBlankLine = '^\s*\(%.*\)\?$'
let s:erlangCompletionPath = expand('<sfile>:p:h') . '/erlang_completion.erl'
if !exists('g:erlangCompletionGrep')
let g:erlangCompletionGrep = 'grep'
endif
if !exists('g:erlangManSuffix')
let g:erlangManSuffix = ''
endif
if !exists('g:erlangManPath')
let g:erlangManPath = '/usr/lib/erlang/man'
endif
if !exists('g:erlangCompletionDisplayDoc')
let g:erlangCompletionDisplayDoc = 1
endif
" Main function for completion {{{1
function! erlangcomplete#Complete(findstart, base)
" 0) Init {{{2
let lnum = line('.')
let column = col('.')
let line = strpart(getline('.'), 0, column - 1)
" 1) First, check if completion is impossible {{{2
if line =~ '[^~\\]%'
return -1
endif
"echo "line[col - 1]:" . line[column - 1] . " line[col - 2]:" . line[column - 2] . "\n" . line . "\n"
" 2) Check if the char to the left of us are part of a function call {{{2
"
" Nothing interesting is written at the char just before the cursor
" This means _anything_ could be started here
" In this case, keyword completion should probably be used,
" for now we'll only try and complete local functions.
" TODO: Examine if we can stare Identifiers end complete on them
" Is this worth it? Is /completion/ of a "blank" wanted? Can we consider (
" interesting and check if we are in a function call etc.?
if line[column - 2] !~ '[0-9A-Za-z:_-]'
if a:findstart
return column
else
return s:erlangFindLocalFunc(a:base)
endif
endif
" 3) Function in external module {{{2
if line =~ s:erlangExternalFuncBeg
let delimiter = match(line, ':[0-9A-Za-z_-]*$') + 1
if a:findstart
return delimiter
else
let module = matchstr(line[:-2], '\<\k*\>$')
return s:erlangFindExternalFunc(module, a:base)
endif
endif
" 4) Local function {{{2
if line =~ s:erlangLocalFuncBeg
let funcstart = match(line, ':\@<![0-9A-Za-z_-]*$')
if a:findstart
return funcstart
else
return s:erlangFindLocalFunc(a:base)
endif
endif
" 5) Unhandled situation {{{2
if a:findstart
return -1
else
return []
endif
endfunction
" Auxiliary functions for completion {{{1
" Find the next non-blank line {{{2
function s:erlangFindNextNonBlank(lnum)
let lnum = nextnonblank(a:lnum + 1)
let line = getline(lnum)
while line =~ s:ErlangBlankLine && 0 != lnum
let lnum = nextnonblank(lnum + 1)
let line = getline(lnum)
endwhile
return lnum
endfunction
" vim: foldmethod=marker:
" Find external function names {{{2
function s:erlangFindExternalFunc(module, base)
" If it's a local module, try to compile it
if filereadable(a:module . '.erl') && !filereadable(a:module . '.beam')
silent execute '!erlc' a:module . '.erl' '>/dev/null' '2>/dev/null'
redraw!
endif
let functions = system(s:erlangCompletionPath . ' ' . a:module)
for element in sort(split(functions, '\n'))
if match(element, a:base) == 0
let function_name = matchstr(element, a:base . '\w\+')
let number_of_args = matchstr(element, '\d\+', len(function_name))
let number_of_comma = max([number_of_args - 1, 0])
let file_path = g:erlangManPath . '/man?/' . a:module . '\.?' . g:erlangManSuffix
" [:-2] cutting some weird characters at the end
" becouse grep doesn't support multilines, we have to filter
" first by .B and next by looking via function name
" if someone have better idea, please change it
let description = ''
" Don't look man pages if the module is present in the current directory
if g:erlangCompletionDisplayDoc != 0 && !filereadable(a:module . '.erl')
let system_command = g:erlangCompletionGrep . ' -A 1 "\.B" ' . file_path . ' | grep -EZo "\<' .
\ function_name . '\>\((\w+, ){' . number_of_comma . '}[^),]*\) -> .*"'
let description = system(system_command)
let description = description[:-2]
endif
if description == ''
let description = element " if function doesn't have description e.g. lists:rmerge, put rmerge/2 instead
endif
let field = {'word': function_name . '(', 'abbr': description, 'kind': 'f', 'dup': 1} " always duplicate functions
call complete_add(field)
endif
endfor
return []
endfunction
" Find local function names {{{2
function s:erlangFindLocalFunc(base)
" begin at line 1
let lnum = s:erlangFindNextNonBlank(1)
if "" == a:base
let base = '\w' " used to match against word symbol
else
let base = a:base
endif
while 0 != lnum && !complete_check()
let line = getline(lnum)
let function_name = matchstr(line, '^' . base . '[0-9A-Za-z_-]\+(\@=')
if function_name != ""
call complete_add(function_name)
endif
let lnum = s:erlangFindNextNonBlank(lnum)
endwhile
return []
endfunction

View File

@@ -28,43 +28,75 @@ if len(s:goarch) == 0
endif
endif
function! go#complete#PackageMembers(package, member)
silent! let content = system('godoc ' . a:package)
if v:shell_error || !len(content)
return []
endif
let lines = filter(split(content, "\n"),"v:val !~ '^\\s\\+$'")
try
let mx1 = '^\s\+\(\S+\)\s\+=\s\+.*'
let mx2 = '^\%(const\|var\|type\|func\) \([A-Z][^ (]\+\).*'
let candidates =
\ map(filter(copy(lines), 'v:val =~ mx1'), 'substitute(v:val, mx1, "\\1", "")')
\ + map(filter(copy(lines), 'v:val =~ mx2'), 'substitute(v:val, mx2, "\\1", "")')
return filter(candidates, '!stridx(v:val, a:member)')
catch
return []
endtry
endfunction
function! go#complete#Package(ArgLead, CmdLine, CursorPos)
let dirs = []
let words = split(a:CmdLine, '\s\+', 1)
if len(words) > 2
" Complete package members
return go#complete#PackageMembers(words[1], words[2])
endif
if executable('go')
let goroot = substitute(system('go env GOROOT'), '\n', '', 'g')
if v:shell_error
echo '\'go env GOROOT\' failed'
endif
let goroot = substitute(system('go env GOROOT'), '\n', '', 'g')
if v:shell_error
echomsg '\'go env GOROOT\' failed'
endif
else
let goroot = $GOROOT
let goroot = $GOROOT
endif
if len(goroot) != 0 && isdirectory(goroot)
let dirs += [ goroot ]
let dirs += [goroot]
endif
let workspaces = split($GOPATH, ':')
let pathsep = ':'
if s:goos == 'windows'
let pathsep = ';'
endif
let workspaces = split($GOPATH, pathsep)
if workspaces != []
let dirs += workspaces
let dirs += workspaces
endif
if len(dirs) == 0
" should not happen
return []
" should not happen
return []
endif
let ret = {}
for dir in dirs
let root = expand(dir . '/pkg/' . s:goos . '_' . s:goarch)
for i in split(globpath(root, a:ArgLead.'*'), "\n")
if isdirectory(i)
let i .= '/'
elseif i !~ '\.a$'
continue
endif
let i = substitute(substitute(i[len(root)+1:], '[\\]', '/', 'g'), '\.a$', '', 'g')
let ret[i] = i
" this may expand to multiple lines
let root = split(expand(dir . '/pkg/' . s:goos . '_' . s:goarch), "\n")
call add(root, expand(dir . '/src'))
for r in root
for i in split(globpath(r, a:ArgLead.'*'), "\n")
if isdirectory(i)
let i .= '/'
elseif i !~ '\.a$'
continue
endif
let i = substitute(substitute(i[len(r)+1:], '[\\]', '/', 'g'), '\.a$', '', 'g')
let ret[i] = i
endfor
endfor
endfor
return sort(keys(ret))

861
autoload/htmlcomplete.vim Normal file
View File

@@ -0,0 +1,861 @@
" Vim completion script
" Language: HTML and XHTML
" Maintainer: Mikolaj Machowski ( mikmach AT wp DOT pl )
" Last Change: 2006 Oct 19
" Modified: othree <othree@gmail.com>
" Changes: Add HTML5, WAI-ARIA support
" Last Change: 2010 Sep 25
if !exists('g:aria_attributes_complete')
let g:aria_attributes_complete = 1
endif
function! htmlcomplete#CompleteTags(findstart, base)
if a:findstart
" locate the start of the word
let line = getline('.')
let start = col('.') - 1
let curline = line('.')
let compl_begin = col('.') - 2
while start >= 0 && line[start - 1] =~ '\(\k\|[!:.-]\)'
let start -= 1
endwhile
" Handling of entities {{{
if start >= 0 && line[start - 1] =~ '&'
let b:entitiescompl = 1
let b:compl_context = ''
return start
endif
" }}}
" Handling of <style> tag {{{
let stylestart = searchpair('<style\>', '', '<\/style\>', "bnW")
let styleend = searchpair('<style\>', '', '<\/style\>', "nW")
if stylestart != 0 && styleend != 0
if stylestart <= curline && styleend >= curline
let start = col('.') - 1
let b:csscompl = 1
while start >= 0 && line[start - 1] =~ '\(\k\|-\)'
let start -= 1
endwhile
endif
endif
" }}}
" Handling of <script> tag {{{
let scriptstart = searchpair('<script\>', '', '<\/script\>', "bnW")
let scriptend = searchpair('<script\>', '', '<\/script\>', "nW")
if scriptstart != 0 && scriptend != 0
if scriptstart <= curline && scriptend >= curline
let start = col('.') - 1
let b:jscompl = 1
let b:jsrange = [scriptstart, scriptend]
while start >= 0 && line[start - 1] =~ '\k'
let start -= 1
endwhile
" We are inside of <script> tag. But we should also get contents
" of all linked external files and (secondary, less probably) other <script> tags
" This logic could possible be done in separate function - may be
" reused in events scripting (also with option could be reused for
" CSS
let b:js_extfiles = []
let l = line('.')
let c = col('.')
call cursor(1,1)
while search('<\@<=script\>', 'W') && line('.') <= l
if synIDattr(synID(line('.'),col('.')-1,0),"name") !~? 'comment'
let sname = matchstr(getline('.'), '<script[^>]*src\s*=\s*\([''"]\)\zs.\{-}\ze\1')
if filereadable(sname)
let b:js_extfiles += readfile(sname)
endif
endif
endwhile
call cursor(1,1)
let js_scripttags = []
while search('<script\>', 'W') && line('.') < l
if matchstr(getline('.'), '<script[^>]*src') == ''
let js_scripttag = getline(line('.'), search('</script>', 'W'))
let js_scripttags += js_scripttag
endif
endwhile
let b:js_extfiles += js_scripttags
call cursor(l,c)
unlet! l c
endif
endif
" }}}
if !exists("b:csscompl") && !exists("b:jscompl")
let b:compl_context = getline('.')[0:(compl_begin)]
if b:compl_context !~ '<[^>]*$'
" Look like we may have broken tag. Check previous lines.
let i = 1
while 1
let context_line = getline(curline-i)
if context_line =~ '<[^>]*$'
" Yep, this is this line
let context_lines = getline(curline-i, curline-1) + [b:compl_context]
let b:compl_context = join(context_lines, ' ')
break
elseif context_line =~ '>[^<]*$' || i == curline
" We are in normal tag line, no need for completion at all
" OR reached first line without tag at all
let b:compl_context = ''
break
endif
let i += 1
endwhile
" Make sure we don't have counter
unlet! i
endif
let b:compl_context = matchstr(b:compl_context, '.*\zs<.*')
" Return proper start for on-events. Without that beginning of
" completion will be badly reported
if b:compl_context =~? 'on[a-z]*\s*=\s*\(''[^'']*\|"[^"]*\)$'
let start = col('.') - 1
while start >= 0 && line[start - 1] =~ '\k'
let start -= 1
endwhile
endif
" If b:compl_context begins with <? we are inside of PHP code. It
" wasn't closed so PHP completion passed it to HTML
if &filetype =~? 'php' && b:compl_context =~ '^<?'
let b:phpcompl = 1
let start = col('.') - 1
while start >= 0 && line[start - 1] =~ '[a-zA-Z_0-9\x7f-\xff$]'
let start -= 1
endwhile
endif
else
let b:compl_context = getline('.')[0:compl_begin]
endif
return start
else
" Initialize base return lists
let res = []
let res2 = []
" a:base is very short - we need context
let context = b:compl_context
" Check if we should do CSS completion inside of <style> tag
" or JS completion inside of <script> tag or PHP completion in case of <?
" tag AND &ft==php
if exists("b:csscompl")
unlet! b:csscompl
let context = b:compl_context
unlet! b:compl_context
return csscomplete#CompleteCSS(0, context)
elseif exists("b:jscompl")
unlet! b:jscompl
return javascriptcomplete#CompleteJS(0, a:base)
elseif exists("b:phpcompl")
unlet! b:phpcompl
let context = b:compl_context
return phpcomplete#CompletePHP(0, a:base)
else
if len(b:compl_context) == 0 && !exists("b:entitiescompl")
return []
endif
let context = matchstr(b:compl_context, '.\zs.*')
endif
unlet! b:compl_context
" Entities completion {{{
if exists("b:entitiescompl")
unlet! b:entitiescompl
if !exists("b:html_doctype")
call htmlcomplete#CheckDoctype()
endif
if !exists("b:html_omni")
"runtime! autoload/xml/xhtml10s.vim
call htmlcomplete#LoadData()
endif
if g:aria_attributes_complete == 1 && !exists("b:aria_omni")
call htmlcomplete#LoadAria()
endif
let entities = b:html_omni['vimxmlentities']
if len(a:base) == 1
for m in entities
if m =~ '^'.a:base
call add(res, m.';')
endif
endfor
return res
else
for m in entities
if m =~? '^'.a:base
call add(res, m.';')
elseif m =~? a:base
call add(res2, m.';')
endif
endfor
return res + res2
endif
endif
" }}}
if context =~ '>'
" Generally if context contains > it means we are outside of tag and
" should abandon action - with one exception: <style> span { bo
if context =~ 'style[^>]\{-}>[^<]\{-}$'
return csscomplete#CompleteCSS(0, context)
elseif context =~ 'script[^>]\{-}>[^<]\{-}$'
let b:jsrange = [line('.'), search('<\/script\>', 'nW')]
return javascriptcomplete#CompleteJS(0, context)
else
return []
endif
endif
" If context contains > it means we are already outside of tag and we
" should abandon action
" If context contains white space it is attribute.
" It can be also value of attribute.
" We have to get first word to offer proper completions
if context == ''
let tag = ''
else
let tag = split(context)[0]
" Detect if tag is uppercase to return in proper case,
" we need to make it lowercase for processing
if tag =~ '^\u*$'
let uppercase_tag = 1
let tag = tolower(tag)
else
let uppercase_tag = 0
endif
endif
" Get last word, it should be attr name
let attr = matchstr(context, '\S\+="[^"]*$')
if attr == ''
let attr = matchstr(context, '.*\s\zs.*')
endif
" Possible situations where any prediction would be difficult:
" 1. Events attributes
if context =~ '\s'
" Sort out style, class, and on* cases
if context =~? "\\s\\(on[a-z]+\\|id\\|style\\|class\\)\\s*=\\s*[\"']"
" Id, class completion {{{
if context =~? "\\(id\\|class\\)\\s*=\\s*[\"'][a-zA-Z0-9_ -]*$"
if context =~? "class\\s*=\\s*[\"'][a-zA-Z0-9_ -]*$"
let search_for = "class"
elseif context =~? "id\\s*=\\s*[\"'][a-zA-Z0-9_ -]*$"
let search_for = "id"
endif
" Handle class name completion
" 1. Find lines of <link stylesheet>
" 1a. Check file for @import
" 2. Extract filename(s?) of stylesheet,
call cursor(1,1)
let head = getline(search('<head\>'), search('<\/head>'))
let headjoined = join(copy(head), ' ')
if headjoined =~ '<style'
" Remove possibly confusing CSS operators
let stylehead = substitute(headjoined, '+>\*[,', ' ', 'g')
if search_for == 'class'
let styleheadlines = split(stylehead)
let headclasslines = filter(copy(styleheadlines), "v:val =~ '\\([a-zA-Z0-9:]\\+\\)\\?\\.[a-zA-Z0-9_-]\\+'")
else
let stylesheet = split(headjoined, '[{}]')
" Get all lines which fit id syntax
let classlines = filter(copy(stylesheet), "v:val =~ '#[a-zA-Z0-9_-]\\+'")
" Filter out possible color definitions
call filter(classlines, "v:val !~ ':\\s*#[a-zA-Z0-9_-]\\+'")
" Filter out complex border definitions
call filter(classlines, "v:val !~ '\\(none\\|hidden\\|dotted\\|dashed\\|solid\\|double\\|groove\\|ridge\\|inset\\|outset\\)\\s*#[a-zA-Z0-9_-]\\+'")
let templines = join(classlines, ' ')
let headclasslines = split(templines)
call filter(headclasslines, "v:val =~ '#[a-zA-Z0-9_-]\\+'")
endif
let internal = 1
else
let internal = 0
endif
let styletable = []
let secimportfiles = []
let filestable = filter(copy(head), "v:val =~ '\\(@import\\|link.*stylesheet\\)'")
for line in filestable
if line =~ "@import"
let styletable += [matchstr(line, "import\\s\\+\\(url(\\)\\?[\"']\\?\\zs\\f\\+\\ze")]
elseif line =~ "<link"
let styletable += [matchstr(line, "href\\s*=\\s*[\"']\\zs\\f\\+\\ze")]
endif
endfor
for file in styletable
if filereadable(file)
let stylesheet = readfile(file)
let secimport = filter(copy(stylesheet), "v:val =~ '@import'")
if len(secimport) > 0
for line in secimport
let secfile = matchstr(line, "import\\s\\+\\(url(\\)\\?[\"']\\?\\zs\\f\\+\\ze")
let secfile = fnamemodify(file, ":p:h").'/'.secfile
let secimportfiles += [secfile]
endfor
endif
endif
endfor
let cssfiles = styletable + secimportfiles
let classes = []
for file in cssfiles
if filereadable(file)
let stylesheet = readfile(file)
let stylefile = join(stylesheet, ' ')
let stylefile = substitute(stylefile, '+>\*[,', ' ', 'g')
if search_for == 'class'
let stylesheet = split(stylefile)
let classlines = filter(copy(stylesheet), "v:val =~ '\\([a-zA-Z0-9:]\\+\\)\\?\\.[a-zA-Z0-9_-]\\+'")
else
let stylesheet = split(stylefile, '[{}]')
" Get all lines which fit id syntax
let classlines = filter(copy(stylesheet), "v:val =~ '#[a-zA-Z0-9_-]\\+'")
" Filter out possible color definitions
call filter(classlines, "v:val !~ ':\\s*#[a-zA-Z0-9_-]\\+'")
" Filter out complex border definitions
call filter(classlines, "v:val !~ '\\(none\\|hidden\\|dotted\\|dashed\\|solid\\|double\\|groove\\|ridge\\|inset\\|outset\\)\\s*#[a-zA-Z0-9_-]\\+'")
let templines = join(classlines, ' ')
let stylelines = split(templines)
let classlines = filter(stylelines, "v:val =~ '#[a-zA-Z0-9_-]\\+'")
endif
" We gathered classes definitions from all external files
let classes += classlines
endif
endfor
if internal == 1
let classes += headclasslines
endif
if search_for == 'class'
let elements = {}
for element in classes
if element =~ '^\.'
let class = matchstr(element, '^\.\zs[a-zA-Z][a-zA-Z0-9_-]*\ze')
let class = substitute(class, ':.*', '', '')
if has_key(elements, 'common')
let elements['common'] .= ' '.class
else
let elements['common'] = class
endif
else
let class = matchstr(element, '[a-zA-Z1-6]*\.\zs[a-zA-Z][a-zA-Z0-9_-]*\ze')
let tagname = tolower(matchstr(element, '[a-zA-Z1-6]*\ze.'))
if tagname != ''
if has_key(elements, tagname)
let elements[tagname] .= ' '.class
else
let elements[tagname] = class
endif
endif
endif
endfor
if has_key(elements, tag) && has_key(elements, 'common')
let values = split(elements[tag]." ".elements['common'])
elseif has_key(elements, tag) && !has_key(elements, 'common')
let values = split(elements[tag])
elseif !has_key(elements, tag) && has_key(elements, 'common')
let values = split(elements['common'])
else
return []
endif
elseif search_for == 'id'
" Find used IDs
" 1. Catch whole file
let filelines = getline(1, line('$'))
" 2. Find lines with possible id
let used_id_lines = filter(filelines, 'v:val =~ "id\\s*=\\s*[\"''][a-zA-Z0-9_-]\\+"')
" 3a. Join all filtered lines
let id_string = join(used_id_lines, ' ')
" 3b. And split them to be sure each id is in separate item
let id_list = split(id_string, 'id\s*=\s*')
" 4. Extract id values
let used_id = map(id_list, 'matchstr(v:val, "[\"'']\\zs[a-zA-Z0-9_-]\\+\\ze")')
let joined_used_id = ','.join(used_id, ',').','
let allvalues = map(classes, 'matchstr(v:val, ".*#\\zs[a-zA-Z0-9_-]\\+")')
let values = []
for element in classes
if joined_used_id !~ ','.element.','
let values += [element]
endif
endfor
endif
" We need special version of sbase
let classbase = matchstr(context, ".*[\"']")
let classquote = matchstr(classbase, '.$')
let entered_class = matchstr(attr, ".*=\\s*[\"']\\zs.*")
for m in sort(values)
if m =~? '^'.entered_class
call add(res, m . classquote)
elseif m =~? entered_class
call add(res2, m . classquote)
endif
endfor
return res + res2
elseif context =~? "style\\s*=\\s*[\"'][^\"']*$"
return csscomplete#CompleteCSS(0, context)
endif
" }}}
" Complete on-events {{{
if context =~? 'on[a-z]*\s*=\s*\(''[^'']*\|"[^"]*\)$'
" We have to:
" 1. Find external files
let b:js_extfiles = []
let l = line('.')
let c = col('.')
call cursor(1,1)
while search('<\@<=script\>', 'W') && line('.') <= l
if synIDattr(synID(line('.'),col('.')-1,0),"name") !~? 'comment'
let sname = matchstr(getline('.'), '<script[^>]*src\s*=\s*\([''"]\)\zs.\{-}\ze\1')
if filereadable(sname)
let b:js_extfiles += readfile(sname)
endif
endif
endwhile
" 2. Find at least one <script> tag
call cursor(1,1)
let js_scripttags = []
while search('<script\>', 'W') && line('.') < l
if matchstr(getline('.'), '<script[^>]*src') == ''
let js_scripttag = getline(line('.'), search('</script>', 'W'))
let js_scripttags += js_scripttag
endif
endwhile
let b:js_extfiles += js_scripttags
" 3. Proper call for javascriptcomplete#CompleteJS
call cursor(l,c)
let js_context = matchstr(a:base, '\k\+$')
let js_shortcontext = substitute(a:base, js_context.'$', '', '')
let b:compl_context = context
let b:jsrange = [l, l]
unlet! l c
return javascriptcomplete#CompleteJS(0, js_context)
endif
" }}}
let stripbase = matchstr(context, ".*\\(on[a-zA-Z]*\\|style\\|class\\)\\s*=\\s*[\"']\\zs.*")
" Now we have context stripped from all chars up to style/class.
" It may fail with some strange style value combinations.
if stripbase !~ "[\"']"
return []
endif
endif
" Value of attribute completion {{{
" If attr contains =\s*[\"'] we catched value of attribute
if attr =~ "=\s*[\"']" || attr =~ "=\s*$"
" Let do attribute specific completion
let attrname = matchstr(attr, '.*\ze\s*=')
let entered_value = matchstr(attr, ".*=\\s*[\"']\\?\\zs.*")
let values = []
" Load data {{{
if !exists("b:html_doctype")
call htmlcomplete#CheckDoctype()
endif
if !exists("b:html_omni")
"runtime! autoload/xml/xhtml10s.vim
call htmlcomplete#LoadData()
endif
if g:aria_attributes_complete == 1 && !exists("b:aria_omni")
call htmlcomplete#LoadAria()
endif
" }}}
if attrname == 'href'
" Now we are looking for local anchors defined by name or id
if entered_value =~ '^#'
let file = join(getline(1, line('$')), ' ')
" Split it be sure there will be one id/name element in
" item, it will be also first word [a-zA-Z0-9_-] in element
let oneelement = split(file, "\\(meta \\)\\@<!\\(name\\|id\\)\\s*=\\s*[\"']")
for i in oneelement
let values += ['#'.matchstr(i, "^[a-zA-Z][a-zA-Z0-9%_-]*")]
endfor
endif
else
if has_key(b:html_omni, tag) && has_key(b:html_omni[tag][1], attrname)
let values = b:html_omni[tag][1][attrname]
elseif attrname =~ '^aria-' && exists("b:aria_omni") && has_key(b:aria_omni['aria_attributes'], attrname)
let values = b:aria_omni['aria_attributes'][attrname]
else
return []
endif
endif
if len(values) == 0
return []
endif
" We need special version of sbase
let attrbase = matchstr(context, ".*[\"']")
let attrquote = matchstr(attrbase, '.$')
if attrquote !~ "['\"]"
let attrquoteopen = '"'
let attrquote = '"'
else
let attrquoteopen = ''
endif
" Multi value attributes don't need ending quote
let info = ''
if has_key(b:html_omni['vimxmlattrinfo'], attrname)
let info = b:html_omni['vimxmlattrinfo'][attrname][0]
elseif exists("b:aria_omni") && has_key(b:aria_omni['vimariaattrinfo'], attrname)
let info = b:aria_omni['vimariaattrinfo'][attrname][0]
endif
if info =~ "^\\*"
let attrquote = ''
endif
if len(entered_value) > 0
if entered_value =~ "\\s$"
let entered_value = ''
else
let entered_value = split(entered_value)[-1]
endif
endif
for m in values
" This if is needed to not offer all completions as-is
" alphabetically but sort them. Those beginning with entered
" part will be as first choices
if m =~ '^'.entered_value
call add(res, attrquoteopen . m . attrquote)
elseif m =~ entered_value
call add(res2, attrquoteopen . m . attrquote)
endif
endfor
return res + res2
endif
" }}}
" Attribute completion {{{
" Shorten context to not include last word
let sbase = matchstr(context, '.*\ze\s.*')
" Load data {{{
if !exists("b:html_doctype")
call htmlcomplete#CheckDoctype()
endif
if !exists("b:html_omni")
call htmlcomplete#LoadData()
endif
if g:aria_attributes_complete == 1 && !exists("b:aria_omni")
call htmlcomplete#LoadAria()
endif
" }}}
if has_key(b:html_omni, tag)
let attrs = keys(b:html_omni[tag][1])
else
return []
endif
if exists("b:aria_omni")
let roles = []
if has_key(b:aria_omni['default_role'], tag)
let roles = [b:aria_omni['default_role'][tag]]
endif
if context =~ 'role='
let start = matchend(context, "role=['\"]")
let end = matchend(context, "[a-z ]\\+['\"]", start)
if start != -1 && end != -1
let roles = split(strpart(context, start, end-start-1), " ")
endif
endif
for i in range(len(roles))
let role = roles[i]
if has_key(b:aria_omni['role_attributes'], role)
let attrs = extend(attrs, b:aria_omni['role_attributes'][role])
endif
endfor
endif
for m in sort(attrs)
if m =~ '^'.attr
call add(res, m)
elseif m =~ attr
call add(res2, m)
endif
endfor
"let menu = res + res2
let menu = res
if has_key(b:html_omni, 'vimxmlattrinfo') || (exists("b:aria_omni") && has_key(b:aria_omni, 'vimariaattrinfo'))
let final_menu = []
for i in range(len(menu))
let item = menu[i]
if has_key(b:html_omni['vimxmlattrinfo'], item)
let m_menu = b:html_omni['vimxmlattrinfo'][item][0]
let m_info = b:html_omni['vimxmlattrinfo'][item][1]
elseif exists("b:aria_omni") && has_key(b:aria_omni['vimariaattrinfo'], item)
let m_menu = b:aria_omni['vimariaattrinfo'][item][0]
let m_info = b:aria_omni['vimariaattrinfo'][item][1]
else
let m_menu = ''
let m_info = ''
endif
if item =~ '^aria-' && exists("b:aria_omni")
if len(b:aria_omni['aria_attributes'][item]) > 0 && b:aria_omni['aria_attributes'][item][0] =~ '^\(BOOL\|'.item.'\)$'
let item = item
let m_menu = 'Bool'
else
let item .= '="'
endif
else
if len(b:html_omni[tag][1][item]) > 0 && b:html_omni[tag][1][item][0] =~ '^\(BOOL\|'.item.'\)$'
let item = item
let m_menu = 'Bool'
else
let item .= '="'
endif
endif
let final_menu += [{'word':item, 'menu':m_menu, 'info':m_info}]
endfor
else
let final_menu = []
for i in range(len(menu))
let item = menu[i]
if len(b:html_omni[tag][1][item]) > 0 && b:html_omni[tag][1][item][0] =~ '^\(BOOL\|'.item.'\)$'
let item = item
else
let item .= '="'
endif
let final_menu += [item]
endfor
return final_menu
endif
return final_menu
endif
" }}}
" Close tag {{{
let b:unaryTagsStack = "area base br col command embed hr img input keygen link meta param source track wbr"
if context =~ '^\/'
if context =~ '^\/.'
return []
else
let opentag = xmlcomplete#GetLastOpenTag("b:unaryTagsStack")
return [opentag.">"]
endif
endif
" }}}
" Load data {{{
if !exists("b:html_doctype")
call htmlcomplete#CheckDoctype()
endif
if !exists("b:html_omni")
"runtime! autoload/xml/xhtml10s.vim
call htmlcomplete#LoadData()
endif
if g:aria_attributes_complete == 1 && !exists("b:aria_omni")
call htmlcomplete#LoadAria()
endif
" }}}
" Tag completion {{{
" Deal with tag completion.
let opentag = tolower(xmlcomplete#GetLastOpenTag("b:unaryTagsStack"))
" MM: TODO: GLOT works always the same but with some weird situation it
" behaves as intended in HTML but screws in PHP
if opentag == '' || &filetype == 'php' && !has_key(b:html_omni, opentag)
" Hack for sometimes failing GetLastOpenTag.
" As far as I tested fail isn't GLOT fault but problem
" of invalid document - not properly closed tags and other mish-mash.
" Also when document is empty. Return list of *all* tags.
let tags = keys(b:html_omni)
call filter(tags, 'v:val !~ "^vimxml"')
else
if has_key(b:html_omni, opentag)
let tags = b:html_omni[opentag][0]
else
return []
endif
endif
" }}}
if exists("uppercase_tag") && uppercase_tag == 1
let context = tolower(context)
endif
" Handle XML keywords: DOCTYPE
if opentag == ''
let tags = [
\ '!DOCTYPE html>',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN" "http://www.w3.org/TR/REC-html40/frameset.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
\ '!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/1999/xhtml">'
\ ] + sort(tags)
endif
"for m in sort(tags)
for m in tags
if m =~ '^'.context
call add(res, m)
elseif m =~ context
call add(res2, m)
endif
endfor
let menu = res + res2
if has_key(b:html_omni, 'vimxmltaginfo')
let final_menu = []
for i in range(len(menu))
let item = menu[i]
if has_key(b:html_omni['vimxmltaginfo'], item)
let m_menu = b:html_omni['vimxmltaginfo'][item][0]
let m_info = b:html_omni['vimxmltaginfo'][item][1]
else
let m_menu = ''
let m_info = ''
endif
if &filetype == 'html' && exists("uppercase_tag") && uppercase_tag == 1 && item !~ 'DOCTYPE'
let item = toupper(item)
endif
if item =~ 'DOCTYPE'
if item =~ 'DTD'
let abbr = 'DOCTYPE '.matchstr(item, 'DTD \zsX\?HTML .\{-}\ze\/\/')
else
let abbr = 'DOCTYPE HTML 5'
endif
else
let abbr = item
endif
let final_menu += [{'abbr':abbr, 'word':item, 'menu':m_menu, 'info':m_info}]
endfor
else
let final_menu = menu
endif
return final_menu
" }}}
endif
endfunction
function! htmlcomplete#LoadAria() " {{{
runtime! autoload/xml/aria.vim
if exists("g:xmldata_aria")
\ && has_key(g:xmldata_aria, 'default_role')
\ && has_key(g:xmldata_aria, 'role_attributes')
\ && has_key(g:xmldata_aria, 'vimariaattrinfo')
\ && has_key(g:xmldata_aria, 'aria_attributes')
let b:aria_omni = g:xmldata_aria
else
let g:aria_attributes_complete = 0
endif
endfunction
" }}}
function! htmlcomplete#LoadData() " {{{
if !exists("b:html_omni_flavor")
if &filetype == 'html'
let b:html_omni_flavor = 'html401t'
else
let b:html_omni_flavor = 'xhtml10s'
endif
endif
" With that if we still have bloated memory but create new buffer
" variables only by linking to existing g:variable, not sourcing whole
" file.
if exists('g:xmldata_'.b:html_omni_flavor)
exe 'let b:html_omni = g:xmldata_'.b:html_omni_flavor
else
exe 'runtime! autoload/xml/'.b:html_omni_flavor.'.vim'
exe 'let b:html_omni = g:xmldata_'.b:html_omni_flavor
endif
endfunction
" }}}
function! htmlcomplete#CheckDoctype() " {{{
if exists('b:html_omni_flavor')
let old_flavor = b:html_omni_flavor
else
let old_flavor = ''
endif
let i = 1
while i < 10 && i < line("$")
let line = getline(i)
if line =~ '<!DOCTYPE.*\<DTD HTML 3\.2'
let b:html_omni_flavor = 'html32'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD HTML 4\.0 Transitional'
let b:html_omni_flavor = 'html40t'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD HTML 4\.0 Frameset'
let b:html_omni_flavor = 'html40f'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD HTML 4\.0'
let b:html_omni_flavor = 'html40s'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD HTML 4\.01 Transitional'
let b:html_omni_flavor = 'html401t'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD HTML 4\.01 Frameset'
let b:html_omni_flavor = 'html401f'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD HTML 4\.01'
let b:html_omni_flavor = 'html401s'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD XHTML 1\.0 Transitional'
let b:html_omni_flavor = 'xhtml10t'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD XHTML 1\.0 Frameset'
let b:html_omni_flavor = 'xhtml10f'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD XHTML 1\.0 Strict'
let b:html_omni_flavor = 'xhtml10s'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE.*\<DTD XHTML 1\.1'
let b:html_omni_flavor = 'xhtml11'
let b:html_doctype = 1
break
elseif line =~ '<!DOCTYPE html'
let b:html_omni_flavor = 'html5'
let b:html_doctype = 1
break
endif
let i += 1
endwhile
if !exists("b:html_doctype")
return
else
" Tie g:xmldata with b:html_omni this way we need to sourca data file only
" once, not every time per buffer.
if old_flavor == b:html_omni_flavor
return
else
if exists('g:xmldata_'.b:html_omni_flavor)
exe 'let b:html_omni = g:xmldata_'.b:html_omni_flavor
else
exe 'runtime! autoload/xml/'.b:html_omni_flavor.'.vim'
exe 'let b:html_omni = g:xmldata_'.b:html_omni_flavor
endif
return
endif
endif
endfunction
" }}}
" vim:set foldmethod=marker:

File diff suppressed because it is too large Load Diff

232
autoload/xml/aria.vim Normal file
View File

@@ -0,0 +1,232 @@
" Vim completion for WAI-ARIA data file
" Language: HTML + WAI-ARIA
" Maintainer: othree <othree@gmail.com>
" Last Change: 2010 Sep 09
" WAI_ARIA: {{{
" Ref: http://www.w3.org/TR/wai-aria/
" Version: Draft 15 December 2009
let abstract_role = {}
let role_attributes = {}
let default_role = {}
" Ref: http://www.w3.org/TR/wai-aria/roles
" Version: Draft 15 December 2009
let widget_role = ['alert', 'alertdialog', 'button', 'checkbox', 'combobox', 'dialog', 'gridcell', 'link', 'log', 'marquee', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'progressbar', 'radio', 'radiogroup', 'scrollbar', 'slider', 'spinbutton', 'status', 'tab', 'tabpanel', 'textbox', 'timer', 'tooltip', 'treeitem', 'combobox', 'grid', 'listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid']
let document_structure = ['article', 'columnheader', 'definition', 'directory', 'document', 'group', 'heading', 'img', 'list', 'listitem', 'math', 'note', 'presentation', 'region', 'row', 'rowheader', 'separator']
let landmark_role = ['application', 'banner', 'complementary', 'contentinfo', 'form', 'main', 'navigation', 'search']
let role = extend(widget_role, document_structure)
let role = extend(role, landmark_role)
" http://www.w3.org/TR/wai-aria/states_and_properties#state_prop_taxonomy
"let global_states_and_properties = {'aria-atomic': ['true', 'false'], 'aria-busy': ['true', 'false'], 'aria-controls': [], 'aria-describedby': [], 'aria-disabled': ['true', 'false'], 'aria-dropeffect': ['copy', 'move', 'link', 'execute', 'popup', 'none'], 'aria-flowto': [], 'aria-grabbed': ['true', 'false', 'undefined'], 'aria-haspopup': ['true', 'false'], 'aria-hidden': ['true', 'false'], 'aria-invalid': ['grammar', 'spelling', 'true', 'false'], 'aria-label': [], 'aria-labelledby': [], 'aria-live': ['off', 'polite', 'assertive'], 'aria-owns': [], 'aria-relevant': ['additions', 'removals', 'text', 'all']}
let widget_attributes = {'aria-autocomplete': ['inline', 'list', 'both', 'none'], 'aria-checked': ['true', 'false', 'mixed', 'undefined'], 'aria-disabled': ['true', 'false'], 'aria-expanded': ['true', 'false', 'undefined'], 'aria-haspopup': ['true', 'false'], 'aria-hidden': ['true', 'false'], 'aria-invalid': ['grammar', 'spelling', 'true', 'false'], 'aria-label': [], 'aria-level': [], 'aria-multiline': ['true', 'false'], 'aria-multiselectable': ['true', 'false'], 'aria-orientation': ['horizontal', 'vertical'], 'aria-pressed': ['true', 'false', 'mixed', 'undefined'], 'aria-readonly': ['true', 'false'], 'aria-required': ['true', 'false'], 'aria-selected': ['true', 'false', 'undefined'], 'aria-sort': ['ascending', 'descending', 'none', 'other'], 'aria-valuemax': [], 'aria-valuemin': [], 'aria-valuenow': [], 'aria-valuetext': []}
let live_region_attributes = {'aria-atomic': ['true', 'false'], 'aria-busy': ['true', 'false'], 'aria-live': ['off', 'polite', 'assertive'], 'aria-relevant': ['additions', 'removals', 'text', 'all', 'additions text']}
let drag_and_drop_attributes = {'aria-dropeffect': ['copy', 'move', 'link', 'execute', 'popup', 'none'], 'aria-grabbed': ['true', 'false', 'undefined']}
let relationship_attributes = {'aria-activedescendant': [], 'aria-controls': [], 'aria-describedby': [], 'aria-flowto': [], 'aria-labelledby': [], 'aria-owns': [], 'aria-posinset': [], 'aria-setsize': []}
let aria_attributes = widget_attributes
let aria_attributes = extend(aria_attributes, live_region_attributes)
let aria_attributes = extend(aria_attributes, drag_and_drop_attributes)
let aria_attributes = extend(aria_attributes, relationship_attributes)
" Abstract Roles
let abstract_role['roletype'] = ['aria-atomic', 'aria-busy', 'aria-controls', 'aria-describedby', 'aria-disabled', 'aria-dropeffect', 'aria-flowto', 'aria-grabbed', 'aria-haspopup', 'aria-hidden', 'aria-invalid', 'aria-label', 'aria-labelledby', 'aria-live', 'aria-owns', 'aria-relevant']
let role_attributes['default'] = abstract_role['roletype']
let abstract_role['structure'] = abstract_role['roletype']
let abstract_role['widget'] = abstract_role['roletype']
let abstract_role['window'] = abstract_role['roletype'] + ['aria-expanded']
let abstract_role['composite'] = abstract_role['widget'] + ['aria-activedescendant']
let abstract_role['input'] = abstract_role['widget']
let abstract_role['section'] = abstract_role['structure'] + ['aria-expanded']
let abstract_role['sectionhead'] = abstract_role['structure'] + ['aria-expanded']
let role_attributes['group'] = abstract_role['section']
let abstract_role['select'] = abstract_role['composite'] + role_attributes['group'] + abstract_role['input']
let abstract_role['range'] = abstract_role['input'] + ['aria-valuemax', 'aria-valuemin', 'aria-valuenow', 'aria-valuetext']
let role_attributes['region'] = abstract_role['section']
let abstract_role['landmark'] = role_attributes['region']
" Widget Roles
let role_attributes['list'] = role_attributes['region']
let role_attributes['listitem'] = abstract_role['section']
let role_attributes['dialog'] = abstract_role['window']
let role_attributes['menuitem'] = abstract_role['input']
let role_attributes['checkbox'] = abstract_role['input'] + ['aria-checked']
let role_attributes['menuitemcheckbox'] = role_attributes['menuitem'] + role_attributes['checkbox']
let role_attributes['option'] = abstract_role['input'] + ['aria-checked', 'aria-posinset', 'aria-selected', 'aria-setsize']
let role_attributes['radio'] = role_attributes['checkbox'] + role_attributes['option']
let role_attributes['directory'] = role_attributes['list']
let role_attributes['alert'] = role_attributes['region']
let role_attributes['alertdialog'] = role_attributes['alert'] + role_attributes['dialog']
let role_attributes['button'] = role_attributes['region'] + role_attributes['menuitemcheckbox']
let role_attributes['combobox'] = abstract_role['select'] + ['aria-expanded', 'aria-required']
let role_attributes['gridcell'] = abstract_role['section'] + abstract_role['widget']
let role_attributes['link'] = abstract_role['widget']
let role_attributes['log'] = role_attributes['region']
let role_attributes['marquee'] = role_attributes['region']
let role_attributes['menuitemradio'] = role_attributes['menuitemcheckbox'] + role_attributes['radio']
let role_attributes['progressbar'] = abstract_role['widget'] + ['aria-valuemax', 'aria-valuemin', 'aria-valuenow', 'aria-valuetext']
let role_attributes['radiogroup'] = abstract_role['select'] + ['aria-required']
let role_attributes['scrollbar'] = abstract_role['range'] + ['aria-controls', 'aria-orientation', 'aria-valuemax', 'aria-valuemin', 'aria-valuenow']
let role_attributes['slider'] = abstract_role['range'] + ['aria-valuemax', 'aria-valuemin', 'aria-valuenow']
let role_attributes['spinbutton'] = abstract_role['composite'] + abstract_role['range'] + ['aria-required']
let role_attributes['status'] = abstract_role['composite'] + role_attributes['region']
let role_attributes['tab'] = abstract_role['sectionhead'] + abstract_role['widget'] + ['aria-selected']
let role_attributes['tabpanel'] = role_attributes['region']
let role_attributes['textbox'] = abstract_role['input'] + ['aria-autocomplete', 'aria-multiline', 'aria-readonly', 'aria-required']
let role_attributes['timer'] = role_attributes['status']
let role_attributes['tooltip'] = abstract_role['section']
let role_attributes['treeitem'] = role_attributes['listitem'] + role_attributes['option']
let role_attributes['grid'] = abstract_role['composite'] + role_attributes['region'] + ['aria-level', 'aria-multiselectable', 'aria-readonly']
let role_attributes['listbox'] = role_attributes['list'] + abstract_role['select'] + ['aria-multiselectable', 'aria-required']
let role_attributes['menu'] = role_attributes['list'] + abstract_role['select']
let role_attributes['menubar'] = role_attributes['menu']
let role_attributes['tablist'] = abstract_role['composite'] + role_attributes['directory']
let role_attributes['toolbar'] = role_attributes['group']
let role_attributes['tree'] = abstract_role['select'] + ['aria-multiselectable', 'aria-required']
let role_attributes['treegrid'] = role_attributes['grid'] + role_attributes['tree']
" Document Structure
let role_attributes['document'] = abstract_role['structure'] + ['aria-expanded']
let role_attributes['article'] = role_attributes['document'] + role_attributes['region']
let role_attributes['columnheader'] = role_attributes['gridcell'] + abstract_role['sectionhead'] + ['aria-sort']
let role_attributes['definition'] = abstract_role['section']
let role_attributes['heading'] = abstract_role['sectionhead'] + ['aria-level']
let role_attributes['img'] = abstract_role['section']
let role_attributes['math'] = abstract_role['section']
let role_attributes['note'] = abstract_role['section']
let role_attributes['presentation'] = abstract_role['structure']
let role_attributes['row'] = role_attributes['group'] + ['aria-level', 'aria-selected']
let role_attributes['rowheader'] = role_attributes['gridcell'] + abstract_role['sectionhead']
let role_attributes['separator'] = abstract_role['structure'] + ['aria-expanded']
" Landmark Roles
let role_attributes['application'] = abstract_role['landmark']
let role_attributes['banner'] = abstract_role['landmark']
let role_attributes['complementary'] = abstract_role['landmark']
let role_attributes['contentinfo'] = abstract_role['landmark']
let role_attributes['form'] = abstract_role['landmark']
let role_attributes['main'] = abstract_role['landmark']
let role_attributes['navigation'] = abstract_role['landmark']
let role_attributes['search'] = abstract_role['landmark']
" http://www.w3.org/TR/wai-aria/states_and_properties#state_prop_def
let aria_attributes_value = {
\ 'aria-autocomplete': ['ID', ''],
\ 'aria-checked': ['Token', ''],
\ 'aria-disabled': ['true/false', ''],
\ 'aria-expanded': ['Token', ''],
\ 'aria-haspopup': ['true/false', ''],
\ 'aria-hidden': ['true/false', ''],
\ 'aria-invalid': ['Token', ''],
\ 'aria-label': ['String', ''],
\ 'aria-level': ['Int', ''],
\ 'aria-multiline': ['true/false', ''],
\ 'aria-multiselectable': ['true/false', ''],
\ 'aria-orientation': ['Token', ''],
\ 'aria-pressed': ['Token', ''],
\ 'aria-readonly': ['true/false', ''],
\ 'aria-required': ['true/false', ''],
\ 'aria-selected': ['Token', ''],
\ 'aria-sort': ['Token', ''],
\ 'aria-valuemax': ['Number', ''],
\ 'aria-valuemin': ['Number', ''],
\ 'aria-valuenow': ['Number', ''],
\ 'aria-valuetext': ['String', ''],
\ 'aria-atomic': ['true/false', ''],
\ 'aria-busy': ['true/false', ''],
\ 'aria-live': ['Token', ''],
\ 'aria-relevant': ['*Token', ''],
\ 'aria-dropeffect': ['*Token', ''],
\ 'aria-grabbed': ['Token', ''],
\ 'aria-activedescendant': ['ID', ''],
\ 'aria-controls': ['*ID', ''],
\ 'aria-describedby': ['*ID', ''],
\ 'aria-flowto': ['*ID', ''],
\ 'aria-labelledby': ['*ID', ''],
\ 'aria-owns': ['*ID', ''],
\ 'aria-posinset': ['Int', ''],
\ 'aria-setsize': ['Int', '']
\ }
" http://dev.w3.org/html5/spec/content-models.html#annotations-for-assistive-technology-products-aria
let default_role = {
\ 'a': 'link',
\ 'area': 'link',
\ 'body': 'document',
\ 'button': 'button',
\ 'datalist': 'listbox',
\ 'h1': 'heading',
\ 'h2': 'heading',
\ 'h3': 'heading',
\ 'h4': 'heading',
\ 'h5': 'heading',
\ 'h6': 'heading',
\ 'hgroup': 'heading',
\ 'hr': 'separator',
\ 'img[alt=]': 'presentation',
\ 'input[type=button]': 'button',
\ 'input[type=email]': 'textbox',
\ 'input[type=image]': 'button',
\ 'input[type=number]': 'spinbutton',
\ 'input[type=password]': 'textbox',
\ 'input[type=range]': 'slider',
\ 'input[type=reset]': 'button',
\ 'input[type=search]': 'textbox',
\ 'input[type=submit]': 'button',
\ 'input[type=tel]': 'textbox',
\ 'input[type=text]': 'textbox',
\ 'input[list]': 'combobox',
\ 'input[type=url]': 'textbox',
\ 'input': 'textbox',
\ 'keygen': 'default',
\ 'label': 'default',
\ 'menu[type=list]': 'menu',
\ 'menu[type=toolbar]': 'toolbar',
\ 'menu': 'default',
\ 'link': 'link',
\ 'nav': 'navigation',
\ 'optgroup': 'default',
\ 'option': 'option',
\ 'progress': 'progressbar',
\ 'select': 'listbox',
\ 'summary': 'heading',
\ 'tbody': 'rowgroup',
\ 'td': 'gridcell',
\ 'textarea': 'textbox',
\ 'tfoot': 'rowgroup',
\ 'th[scope=col]': 'columnheader',
\ 'th[scope=row]': 'rowheader',
\ 'tr': 'row',
\ 'address': 'default',
\ 'article': 'article',
\ 'aside': 'note',
\ 'footer': 'default',
\ 'header': 'default',
\ 'details': 'group',
\ 'img': 'img',
\ 'input[type=checkbox]': 'checkbox',
\ 'input[type=radio]': 'radio',
\ 'li': 'listitem',
\ 'ol': 'list',
\ 'output': 'status',
\ 'section': 'region',
\ 'table': 'grid',
\ 'ul': 'list',
\ }
" }}}
let g:xmldata_aria = {
\ 'aria_attributes': aria_attributes,
\ 'role_attributes': role_attributes,
\ 'default_role': default_role,
\ 'vimariaattrinfo': aria_attributes_value
\ }

813
autoload/xml/html5.vim Normal file
View File

@@ -0,0 +1,813 @@
" Vim completion for HTML5 data file
" Language: HTML5
" Maintainer: othree <othree@gmail.com>
" Last Change: 2011 Apr 9
" Lang Tag: {{{
" Ref: http://www.iana.org/assignments/language-subtag-registry
" Version: 2010/09/07
" Description: only get two-letter language tag
let lang_tag = [
\ 'aa', 'ab', 'ae', 'af', 'ak', 'am', 'an', 'ar', 'as', 'av', 'ay', 'az', 'ba', 'be', 'bg', 'bh', 'bi', 'bm',
\ 'bn', 'bo', 'br', 'bs', 'ca', 'ce', 'ch', 'co', 'cr', 'cs', 'cu', 'cv', 'cy', 'da', 'de', 'dv', 'dz', 'ee',
\ 'el', 'en', 'eo', 'es', 'et', 'eu', 'fa', 'ff', 'fi', 'fj', 'fo', 'fr', 'fy', 'ga', 'gd', 'gl', 'gn', 'gu',
\ 'gv', 'ha', 'he', 'hi', 'ho', 'hr', 'ht', 'hu', 'hy', 'hz', 'ia', 'id', 'ie', 'ig', 'ii', 'ik', 'in', 'io',
\ 'is', 'it', 'iu', 'iw', 'ja', 'ji', 'jv', 'jw', 'ka', 'kg', 'ki', 'kj', 'kk', 'kl', 'km', 'kn', 'ko', 'kr',
\ 'ks', 'ku', 'kv', 'kw', 'ky', 'la', 'lb', 'lg', 'li', 'ln', 'lo', 'lt', 'lu', 'lv', 'mg', 'mh', 'mi', 'mk',
\ 'ml', 'mn', 'mo', 'mr', 'ms', 'mt', 'my', 'na', 'nb', 'nd', 'ne', 'ng', 'nl', 'nn', 'no', 'nr', 'nv', 'ny',
\ 'oc', 'oj', 'om', 'or', 'os', 'pa', 'pi', 'pl', 'ps', 'pt', 'qu', 'rm', 'rn', 'ro', 'ru', 'rw', 'sa', 'sc',
\ 'sd', 'se', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'sr', 'ss', 'st', 'su', 'sv', 'sw', 'ta',
\ 'te', 'tg', 'th', 'ti', 'tk', 'tl', 'tn', 'to', 'tr', 'ts', 'tt', 'tw', 'ty', 'ug', 'uk', 'ur', 'uz', 've',
\ 'vi', 'vo', 'wa', 'wo', 'xh', 'yi', 'yo', 'za', 'zh', 'zu', 'zh-CN', 'zh-TW']
" }}}
" Charset: {{{
" Ref: http://www.iana.org/assignments/character-sets
" Version: 2010/09/07
let charset = [
\ 'ANSI_X3.4-1968', 'ISO_8859-1:1987', 'ISO_8859-2:1987', 'ISO_8859-3:1988', 'ISO_8859-4:1988', 'ISO_8859-5:1988',
\ 'ISO_8859-6:1987', 'ISO_8859-7:1987', 'ISO_8859-8:1988', 'ISO_8859-9:1989', 'ISO-8859-10', 'ISO_6937-2-add', 'JIS_X0201',
\ 'JIS_Encoding', 'Shift_JIS', 'Extended_UNIX_Code_Packed_Format_for_Japanese', 'Extended_UNIX_Code_Fixed_Width_for_Japanese',
\ 'BS_4730', 'SEN_850200_C', 'IT', 'ES', 'DIN_66003', 'NS_4551-1', 'NF_Z_62-010', 'ISO-10646-UTF-1', 'ISO_646.basic:1983',
\ 'INVARIANT', 'ISO_646.irv:1983', 'NATS-SEFI', 'NATS-SEFI-ADD', 'NATS-DANO', 'NATS-DANO-ADD', 'SEN_850200_B', 'KS_C_5601-1987',
\ 'ISO-2022-KR', 'EUC-KR', 'ISO-2022-JP', 'ISO-2022-JP-2', 'JIS_C6220-1969-jp', 'JIS_C6220-1969-ro', 'PT', 'greek7-old',
\ 'latin-greek', 'NF_Z_62-010_(1973)', 'Latin-greek-1', 'ISO_5427', 'JIS_C6226-1978', 'BS_viewdata', 'INIS', 'INIS-8',
\ 'INIS-cyrillic', 'ISO_5427:1981', 'ISO_5428:1980', 'GB_1988-80', 'GB_2312-80', 'NS_4551-2', 'videotex-suppl', 'PT2',
\ 'ES2', 'MSZ_7795.3', 'JIS_C6226-1983', 'greek7', 'ASMO_449', 'iso-ir-90', 'JIS_C6229-1984-a', 'JIS_C6229-1984-b',
\ 'JIS_C6229-1984-b-add', 'JIS_C6229-1984-hand', 'JIS_C6229-1984-hand-add', 'JIS_C6229-1984-kana', 'ISO_2033-1983',
\ 'ANSI_X3.110-1983', 'T.61-7bit', 'T.61-8bit', 'ECMA-cyrillic', 'CSA_Z243.4-1985-1', 'CSA_Z243.4-1985-2', 'CSA_Z243.4-1985-gr',
\ 'ISO_8859-6-E', 'ISO_8859-6-I', 'T.101-G2', 'ISO_8859-8-E', 'ISO_8859-8-I', 'CSN_369103', 'JUS_I.B1.002', 'IEC_P27-1',
\ 'JUS_I.B1.003-serb', 'JUS_I.B1.003-mac', 'greek-ccitt', 'NC_NC00-10:81', 'ISO_6937-2-25', 'GOST_19768-74', 'ISO_8859-supp',
\ 'ISO_10367-box', 'latin-lap', 'JIS_X0212-1990', 'DS_2089', 'us-dk', 'dk-us', 'KSC5636', 'UNICODE-1-1-UTF-7', 'ISO-2022-CN',
\ 'ISO-2022-CN-EXT', 'UTF-8', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16', 'GBK', 'GB18030', 'OSD_EBCDIC_DF04_15',
\ 'OSD_EBCDIC_DF03_IRV', 'OSD_EBCDIC_DF04_1', 'ISO-11548-1', 'KZ-1048', 'ISO-10646-UCS-2', 'ISO-10646-UCS-4', 'ISO-10646-UCS-Basic',
\ 'ISO-10646-Unicode-Latin1', 'ISO-10646-J-1', 'ISO-Unicode-IBM-1261', 'ISO-Unicode-IBM-1268', 'ISO-Unicode-IBM-1276',
\ 'ISO-Unicode-IBM-1264', 'ISO-Unicode-IBM-1265', 'UNICODE-1-1', 'SCSU', 'UTF-7', 'UTF-16BE', 'UTF-16LE', 'UTF-16', 'CESU-8',
\ 'UTF-32', 'UTF-32BE', 'UTF-32LE', 'BOCU-1', 'ISO-8859-1-Windows-3.0-Latin-1', 'ISO-8859-1-Windows-3.1-Latin-1',
\ 'ISO-8859-2-Windows-Latin-2', 'ISO-8859-9-Windows-Latin-5', 'hp-roman8', 'Adobe-Standard-Encoding', 'Ventura-US',
\ 'Ventura-International', 'DEC-MCS', 'IBM850', 'PC8-Danish-Norwegian', 'IBM862', 'PC8-Turkish', 'IBM-Symbols', 'IBM-Thai',
\ 'HP-Legal', 'HP-Pi-font', 'HP-Math8', 'Adobe-Symbol-Encoding', 'HP-DeskTop', 'Ventura-Math', 'Microsoft-Publishing',
\ 'Windows-31J', 'GB2312', 'Big5', 'macintosh', 'IBM037', 'IBM038', 'IBM273', 'IBM274', 'IBM275', 'IBM277', 'IBM278',
\ 'IBM280', 'IBM281', 'IBM284', 'IBM285', 'IBM290', 'IBM297', 'IBM420', 'IBM423', 'IBM424', 'IBM437', 'IBM500', 'IBM851',
\ 'IBM852', 'IBM855', 'IBM857', 'IBM860', 'IBM861', 'IBM863', 'IBM864', 'IBM865', 'IBM868', 'IBM869', 'IBM870', 'IBM871',
\ 'IBM880', 'IBM891', 'IBM903', 'IBM904', 'IBM905', 'IBM918', 'IBM1026', 'EBCDIC-AT-DE', 'EBCDIC-AT-DE-A', 'EBCDIC-CA-FR',
\ 'EBCDIC-DK-NO', 'EBCDIC-DK-NO-A', 'EBCDIC-FI-SE', 'EBCDIC-FI-SE-A', 'EBCDIC-FR', 'EBCDIC-IT', 'EBCDIC-PT', 'EBCDIC-ES',
\ 'EBCDIC-ES-A', 'EBCDIC-ES-S', 'EBCDIC-UK', 'EBCDIC-US', 'UNKNOWN-8BIT', 'MNEMONIC', 'MNEM', 'VISCII', 'VIQR', 'KOI8-R',
\ 'HZ-GB-2312', 'IBM866', 'IBM775', 'KOI8-U', 'IBM00858', 'IBM00924', 'IBM01140', 'IBM01141', 'IBM01142', 'IBM01143',
\ 'IBM01144', 'IBM01145', 'IBM01146', 'IBM01147', 'IBM01148', 'IBM01149', 'Big5-HKSCS', 'IBM1047', 'PTCP154', 'Amiga-1251',
\ 'KOI7-switched', 'BRF', 'TSCII', 'windows-1250', 'windows-1251', 'windows-1252', 'windows-1253', 'windows-1254', 'windows-1255',
\ 'windows-1256', 'windows-1257', 'windows-1258', 'TIS-620', ]
" }}}
" Attributes_and_Settings: {{{
let core_attributes = {'accesskey': [], 'class': [], 'contenteditable': ['true', 'false', ''], 'contextmenu': [], 'dir': ['ltr', 'rtl'], 'draggable': ['true', 'false'], 'hidden': ['hidden', ''], 'id': [], 'is': [], 'lang': lang_tag, 'spellcheck': ['true', 'false', ''], 'style': [], 'tabindex': [], 'title': []}
let xml_attributes = {'xml:lang': lang_tag, 'xml:space': ['preserve'], 'xml:base': [], 'xmlns': ['http://www.w3.org/1999/xhtml', 'http://www.w3.org/1998/Math/MathML', 'http://www.w3.org/2000/svg', 'http://www.w3.org/1999/xlink']}
let body_attributes = {}
let global_attributes = extend(core_attributes, xml_attributes)
if !exists('g:html5_event_handler_attributes_complete')
let g:html5_event_handler_attributes_complete = 1
endif
" http://dev.w3.org/html5/spec/Overview.html#attributes-1
let attributes_value = {
\ 'accept': ['MIME', ''],
\ 'accept-charset': ['Charset', ''],
\ 'accesskey': ['Character', ''],
\ 'action': ['URL', ''],
\ 'alt': ['Text', ''],
\ 'async': ['Bool', ''],
\ 'autocomplete': ['on/off', ''],
\ 'autofocus': ['Bool', ''],
\ 'autoplay': ['Bool', ''],
\ 'border': ['1', ''],
\ 'challenge': ['Text', ''],
\ 'charset': ['Charset', ''],
\ 'checked': ['Bool', ''],
\ 'cite': ['URL', ''],
\ 'class': ['*Token', ''],
\ 'cols': ['Int', ''],
\ 'colspan': ['Int', ''],
\ 'content': ['Text', ''],
\ 'contenteditable': ['true/false', ''],
\ 'contextmenu': ['ID', ''],
\ 'controls': ['Bool', ''],
\ 'coords': ['*Int', ''],
\ 'data': ['URL', ''],
\ 'datetime': ['Datetime', ''],
\ 'defer': ['Bool', ''],
\ 'dir': ['ltr/rtl', ''],
\ 'disabled': ['Bool', ''],
\ 'draggable': ['true/false', ''],
\ 'enctype': ['Token', ''],
\ 'extends': ['Text', ''],
\ 'for': ['ID', ''],
\ 'form': ['ID', ''],
\ 'formaction': ['URL', ''],
\ 'formenctype': ['Token', ''],
\ 'formmethod': ['HTTP Method', ''],
\ 'formnovalidate': ['Bool', ''],
\ 'formtarget': ['Name', ''],
\ 'headers': ['*ID', ''],
\ 'height': ['Int', ''],
\ 'hidden': ['Bool', ''],
\ 'high': ['Number', ''],
\ 'href': ['URL', ''],
\ 'hreflang': ['Lang Tag', ''],
\ 'http-equiv': ['Text', ''],
\ 'icon': ['URL', ''],
\ 'id': ['Text', ''],
\ 'ismap': ['Bool', ''],
\ 'keytype': ['Text', ''],
\ 'label': ['Text', ''],
\ 'lang': ['Lang Tag', ''],
\ 'list': ['ID', ''],
\ 'loop': ['Bool', ''],
\ 'low': ['Number', ''],
\ 'manifest': ['URL', ''],
\ 'max': ['Number', ''],
\ 'maxlength': ['Int', ''],
\ 'media': ['Text', ''],
\ 'method': ['HTTP Method', ''],
\ 'min': ['Number', ''],
\ 'multiple': ['Bool', ''],
\ 'name': ['Text', ''],
\ 'novalidate': ['Bool', ''],
\ 'open': ['Bool', ''],
\ 'optimum': ['Number', ''],
\ 'pattern': ['Pattern', ''],
\ 'placeholder': ['Text', ''],
\ 'poster': ['URL', ''],
\ 'preload': ['Token', ''],
\ 'pubdate': ['Bool', ''],
\ 'radiogroup': ['Text', ''],
\ 'readonly': ['Bool', ''],
\ 'rel': ['*Token', ''],
\ 'required': ['Bool', ''],
\ 'reversed': ['Bool', ''],
\ 'rows': ['Int', ''],
\ 'rowspan': ['Int', ''],
\ 'sandbox': ['*Token', ''],
\ 'spellcheck': ['true/false', ''],
\ 'scope': ['Token', ''],
\ 'scoped': ['Bool', ''],
\ 'seamless': ['Bool', ''],
\ 'select': ['Text', ''],
\ 'selected': ['Bool', ''],
\ 'shape': ['Token', ''],
\ 'size': ['Int', ''],
\ 'sizes': ['*Token', ''],
\ 'span': ['Int', ''],
\ 'src': ['Int', ''],
\ 'srcdoc': ['Document', ''],
\ 'start': ['Int', ''],
\ 'step': ['Int', ''],
\ 'style': ['Style', ''],
\ 'summary': ['Text', ''],
\ 'tabindex': ['Int', ''],
\ 'target': ['Name', ''],
\ 'title': ['Text', ''],
\ 'type': ['Token', ''],
\ 'usemap': ['Name', ''],
\ 'value': ['Text', ''],
\ 'width': ['Int', ''],
\ 'wrap': ['soft/hard', ''],
\ 'xml:lang': ['Lang tag', ''],
\ 'xml:base': ['*URI', ''],
\ 'xml:space': ['preserve', ''],
\ 'xmlns': ['URI', ''],
\ 'version': ['HTML+RDFa 1.1', ''],
\ 'role': ['*Token', '']
\ }
if g:html5_event_handler_attributes_complete == 1
let event_handler_attributes = {'onabort': [], 'onblur': [], 'oncanplay': [], 'oncanplaythrough': [], 'onchange': [], 'onclick': [], 'oncontextmenu': [], 'ondblclick': [], 'ondrag': [], 'ondragend': [], 'ondragenter': [], 'ondragleave': [], 'ondragover': [], 'ondragstart': [], 'ondrop': [], 'ondurationchange': [], 'onemptied': [], 'onended': [], 'onerror': [], 'onfocus': [], 'onformchange': [], 'onforminput': [], 'oninput': [], 'oninvalid': [], 'onkeydown': [], 'onkeypress': [], 'onkeyup': [], 'onload': [], 'onloadeddata': [], 'onloadedmetadata': [], 'onloadstart': [], 'onmousedown': [], 'onmousemove': [], 'onmouseout': [], 'onmouseover': [], 'onmouseup': [], 'onmousewheel': [], 'onpause': [], 'onplay': [], 'onplaying': [], 'onprogress': [], 'onratechange': [], 'onreadystatechange': [], 'onscroll': [], 'onseeked': [], 'onseeking': [], 'onselect': [], 'onshow': [], 'onstalled': [], 'onsubmit': [], 'onsuspend': [], 'ontimeupdate': [], 'onvolumechange': [], 'onwaiting': []}
let global_attributes = extend(global_attributes, event_handler_attributes)
let body_attributes = {'onafterprint': [], 'onbeforeprint': [], 'onbeforeunload': [], 'onblur': [], 'onerror': [], 'onfocus': [], 'onhashchange': [], 'onload': [], 'onmessage': [], 'onoffline': [], 'ononline': [], 'onpopstate': [], 'onredo': [], 'onresize': [], 'onstorage': [], 'onundo': [], 'onunload': []}
let event_attributes_value = {
\ 'onabort': ['Script', ''],
\ 'onafterprint': ['Script', ''],
\ 'onbeforeprint': ['Script', ''],
\ 'onbeforeunload': ['Script', ''],
\ 'onblur': ['Script', ''],
\ 'oncanplay': ['Script', ''],
\ 'oncanplaythrough': ['Script', ''],
\ 'onchange': ['Script', ''],
\ 'onclick': ['Script', ''],
\ 'oncontextmenu': ['Script', ''],
\ 'ondblclick': ['Script', ''],
\ 'ondrag': ['Script', ''],
\ 'ondragend': ['Script', ''],
\ 'ondragenter': ['Script', ''],
\ 'ondragleave': ['Script', ''],
\ 'ondragover': ['Script', ''],
\ 'ondragstart': ['Script', ''],
\ 'ondrop': ['Script', ''],
\ 'ondurationchange': ['Script', ''],
\ 'onemptied': ['Script', ''],
\ 'onended': ['Script', ''],
\ 'onerror': ['Script', ''],
\ 'onfocus': ['Script', ''],
\ 'onformchange': ['Script', ''],
\ 'onforminput': ['Script', ''],
\ 'onhashchange': ['Script', ''],
\ 'oninput': ['Script', ''],
\ 'oninvalid': ['Script', ''],
\ 'onkeydown': ['Script', ''],
\ 'onkeypress': ['Script', ''],
\ 'onkeyup': ['Script', ''],
\ 'onload': ['Script', ''],
\ 'onloadeddata': ['Script', ''],
\ 'onloadedmetadata': ['Script', ''],
\ 'onloadstart': ['Script', ''],
\ 'onmessage': ['Script', ''],
\ 'onmousedown': ['Script', ''],
\ 'onmousemove': ['Script', ''],
\ 'onmouseout': ['Script', ''],
\ 'onmouseover': ['Script', ''],
\ 'onmouseup': ['Script', ''],
\ 'onmousewheel': ['Script', ''],
\ 'onoffline': ['Script', ''],
\ 'ononline': ['Script', ''],
\ 'onpagehide': ['Script', ''],
\ 'onpageshow': ['Script', ''],
\ 'onpause': ['Script', ''],
\ 'onplay': ['Script', ''],
\ 'onplaying': ['Script', ''],
\ 'onpopstate': ['Script', ''],
\ 'onprogress': ['Script', ''],
\ 'onratechange': ['Script', ''],
\ 'onreadystatechange': ['Script', ''],
\ 'onredo': ['Script', ''],
\ 'onresize': ['Script', ''],
\ 'onscroll': ['Script', ''],
\ 'onseeked': ['Script', ''],
\ 'onseeking': ['Script', ''],
\ 'onselect': ['Script', ''],
\ 'onshow': ['Script', ''],
\ 'onstalled': ['Script', ''],
\ 'onstorage': ['Script', ''],
\ 'onsubmit': ['Script', ''],
\ 'onsuspend': ['Script', ''],
\ 'ontimeupdate': ['Script', ''],
\ 'onundo': ['Script', ''],
\ 'onunload': ['Script', ''],
\ 'onvolumechange': ['Script', ''],
\ 'onwaiting': ['Script', '']
\ }
let attributes_value = extend(attributes_value, event_attributes_value)
endif
if !exists('g:html5_rdfa_attributes_complete')
let g:html5_rdfa_attributes_complete = 1
endif
if g:html5_rdfa_attributes_complete == 1
" http://www.w3.org/TR/rdfa-syntax/#s_metaAttributes
" http://www.w3.org/TR/rdfa-core/#s_syntax
let relrev = ['chapter', 'contents', 'copyright', 'first', 'glossary', 'help', 'icon', 'index', 'last', 'license', 'meta', 'next', 'p3pv1', 'prev', 'role', 'section', 'stylesheet', 'subsection', 'start', 'top', 'up']
let rdfa_attributes = {'about': [], 'content': [], 'datatype': [], 'prefix': [], 'profile': [], 'property': [], 'resource': [], 'rel': relrev, 'rev': relrev, 'typeof': [], 'vocab': []}
let global_attributes = extend(global_attributes, rdfa_attributes)
let rdfa_attributes_value = {
\ 'about': ['SafeCURIEorCURIEorURI', ''],
\ 'content': ['CDATA String', ''],
\ 'datatype': ['CURIE', ''],
\ 'prefix': ['*Prefix', ''],
\ 'profile': ['String', ''],
\ 'property': ['*TERMorCURIEorAbsURIs', ''],
\ 'resource': ['URIorSafeCURIE', ''],
\ 'rel': ['*TERMorCURIEorAbsURIs', ''],
\ 'rev': ['*TERMorCURIEorAbsURIs', ''],
\ 'typeof': ['*TERMorCURIEorAbsURIs', ''],
\ 'vocab': ['URI', '']
\ }
let attributes_value = extend(attributes_value, rdfa_attributes_value)
endif
if !exists('g:html5_microdata_attributes_complete')
let g:html5_microdata_attributes_complete = 1
endif
if g:html5_microdata_attributes_complete == 1
let microdata_attributes = {'itemid': [], 'itemscope': ['itemscope', ''], 'itemtype': [], 'itemprop': [], 'itemref': []}
let global_attributes = extend(global_attributes, microdata_attributes)
let microdata_attributes_value = {
\ 'itemid': ['URI', ''],
\ 'itemscope': ['Bool', ''],
\ 'itemtype': ['URI', ''],
\ 'itemprop': ['String', ''],
\ 'itemref': ['*ID', '']
\ }
let attributes_value = extend(attributes_value, microdata_attributes_value)
endif
" }}}
" WAI_ARIA: {{{
" Ref: http://www.w3.org/TR/wai-aria/
" Version: Draft 15 December 2009
if !exists('g:html5_aria_attributes_complete')
let g:html5_aria_attributes_complete = 1
endif
if g:html5_aria_attributes_complete == 1
" Ref: http://www.w3.org/TR/wai-aria/roles
" Version: Draft 15 December 2009
let widget_role = ['alert', 'alertdialog', 'button', 'checkbox', 'combobox', 'dialog', 'gridcell', 'link', 'log', 'marquee', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'progressbar', 'radio', 'radiogroup', 'scrollbar', 'slider', 'spinbutton', 'status', 'tab', 'tabpanel', 'textbox', 'timer', 'tooltip', 'treeitem', 'combobox', 'grid', 'listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid']
let document_structure = ['article', 'columnheader', 'definition', 'directory', 'document', 'group', 'heading', 'img', 'list', 'listitem', 'math', 'note', 'presentation', 'region', 'row', 'rowheader', 'separator']
let landmark_role = ['application', 'banner', 'complementary', 'contentinfo', 'form', 'main', 'navigation', 'search']
let role = extend(widget_role, document_structure)
let role = extend(role, landmark_role)
let global_attributes = extend(global_attributes, {'role': role})
endif
" }}}
" Ref: http://dev.w3.org/html5/markup/
" Version: Draft 05 April 2011
let phrasing_elements = ['a', 'em', 'strong', 'small', 'mark', 'abbr', 'dfn', 'i', 'b', 'u', 'code', 'var', 'samp', 'kbd', 'sup', 'sub', 'q', 'cite', 'span', 'bdo', 'bdi', 'br', 'wbr', 'ins', 'del', 'img', 'embed', 'object', 'iframe', 'map', 'area', 'script', 'noscript', 'ruby', 'video', 'audio', 'input', 'textarea', 'select', 'button', 'label', 'output', 'datalist', 'keygen', 'progress', 'command', 'canvas', 'time', 'meter', 'data', 'content', 'shadow']
let metadata_elements = ['link', 'style', 'meta', 'script', 'noscript', 'command']
let flow_elements = phrasing_elements + ['p', 'hr', 'pre', 'ul', 'ol', 'dl', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'address', 'blockquote', 'ins', 'del', 'element', 'object', 'main', 'map', 'noscript', 'section', 'nav', 'article', 'aside', 'header', 'footer', 'video', 'audio', 'figure', 'table', 'template', 'form', 'fieldset', 'menu', 'canvas', 'details']
" http://dev.w3.org/html5/spec/Overview.html#linkTypes
let linktypes = ['alternate', 'author', 'bookmark', 'external', 'help', 'icon', 'license', 'next', 'nofollow', 'noreferrer', 'pingback', 'prefetch', 'prev', 'search', 'stylesheet', 'sidebar', 'tag']
" http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html
let linkreltypes = linktypes + ['canonical', 'import']
" a and button are special elements for interactive, some element can't be its descendent
let abutton_dec = 'details\\|embed\\|iframe\\|keygen\\|label\\|menu\\|select\\|textarea'
let g:xmldata_html5 = {
\ 'vimxmlentities': ['AElig', 'Aacute', 'Acirc', 'Agrave', 'Alpha', 'Aring', 'Atilde', 'Auml', 'Beta', 'Ccedil', 'Chi', 'Dagger', 'Delta', 'ETH', 'Eacute', 'Ecirc', 'Egrave', 'Epsilon', 'Eta', 'Euml', 'Gamma', 'Iacute', 'Icirc', 'Igrave', 'Iota', 'Iuml', 'Kappa', 'Lambda', 'Mu', 'Ntilde', 'Nu', 'OElig', 'Oacute', 'Ocirc', 'Ograve', 'Omega', 'Omicron', 'Oslash', 'Otilde', 'Ouml', 'Phi', 'Pi', 'Prime', 'Psi', 'Rho', 'Scaron', 'Sigma', 'THORN', 'Tau', 'Theta', 'Uacute', 'Ucirc', 'Ugrave', 'Upsilon', 'Uuml', 'Xi', 'Yacute', 'Yuml', 'Zeta', 'aacute', 'acirc', 'acute', 'aelig', 'agrave', 'alefsym', 'alpha', 'amp', 'and', 'ang', 'apos', 'aring', 'asymp', 'atilde', 'auml', 'bdquo', 'beta', 'brvbar', 'bull', 'cap', 'ccedil', 'cedil', 'cent', 'chi', 'circ', 'clubs', 'cong', 'copy', 'crarr', 'cup', 'curren', 'dArr', 'dagger', 'darr', 'deg', 'delta', 'diams', 'divide', 'eacute', 'ecirc', 'egrave', 'empty', 'emsp', 'ensp', 'epsilon', 'equiv', 'eta', 'eth', 'euml', 'euro', 'exist', 'fnof', 'forall', 'frac12', 'frac14', 'frac34', 'frasl', 'gamma', 'ge', 'gt', 'hArr', 'harr', 'hearts', 'hellip', 'iacute', 'icirc', 'iexcl', 'igrave', 'image', 'infin', 'int', 'iota', 'iquest', 'isin', 'iuml', 'kappa', 'lArr', 'lambda', 'lang', 'laquo', 'larr', 'lceil', 'ldquo', 'le', 'lfloor', 'lowast', 'loz', 'lrm', 'lsaquo', 'lsquo', 'lt', 'macr', 'mdash', 'micro', 'middot', 'minus', 'mu', 'nabla', 'nbsp', 'ndash', 'ne', 'ni', 'not', 'notin', 'nsub', 'ntilde', 'nu', 'oacute', 'ocirc', 'oelig', 'ograve', 'oline', 'omega', 'omicron', 'oplus', 'or', 'ordf', 'ordm', 'oslash', 'otilde', 'otimes', 'ouml', 'para', 'part', 'permil', 'perp', 'phi', 'pi', 'piv', 'plusmn', 'pound', 'prime', 'prod', 'prop', 'psi', 'quot', 'rArr', 'radic', 'rang', 'raquo', 'rarr', 'rceil', 'rdquo', 'real', 'reg', 'rfloor', 'rho', 'rlm', 'rsaquo', 'rsquo', 'sbquo', 'scaron', 'sdot', 'sect', 'shy', 'sigma', 'sigmaf', 'sim', 'spades', 'sub', 'sube', 'sum', 'sup', 'sup1', 'sup2', 'sup3', 'supe', 'szlig', 'tau', 'there4', 'theta', 'thetasym', 'thinsp', 'thorn', 'tilde', 'times', 'trade', 'uArr', 'uacute', 'uarr', 'ucirc', 'ugrave', 'uml', 'upsih', 'upsilon', 'uuml', 'weierp', 'xi', 'yacute', 'yen', 'yuml', 'zeta', 'zwj', 'zwnj'],
\ 'vimxmlroot': ['html'],
\ 'a': [
\ filter(copy(flow_elements), "!(v:val =~ '". abutton_dec ."')"),
\ extend(copy(global_attributes), {'name': [], 'href': [], 'target': [], 'rel': linktypes, 'hreflang': lang_tag, 'media': [], 'type': []})
\ ],
\ 'abbr': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'address': [
\ filter(copy(flow_elements), "!(v:val =~ 'address\\|nav\\|article\\|header\\|footer\\|section\\|aside\\|h1\\|h2\\|h3\\|h4\\|h5\\|h6')"),
\ global_attributes
\ ],
\ 'area': [
\ [],
\ extend(copy(global_attributes), {'alt': [], 'href': [], 'target': [], 'rel': linktypes, 'media': [], 'hreflang': lang_tag, 'type': [], 'shape': ['rect', 'circle', 'poly', 'default'], 'coords': []})
\ ],
\ 'article': [
\ flow_elements + ['style'],
\ global_attributes
\ ],
\ 'aside': [
\ flow_elements + ['style'],
\ global_attributes
\ ],
\ 'audio': [
\ flow_elements + ['source', 'track'],
\ extend(copy(global_attributes), {'autoplay': ['autoplay', ''], 'preload': ['none', 'metadata', 'auto', ''], 'controls': ['controls', ''], 'loop': ['loop', ''], 'src': []})
\ ],
\ 'b': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'base': [
\ [],
\ extend(copy(global_attributes), {'href': [], 'target': []})
\ ],
\ 'bdo': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'bdi': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'blockquote': [
\ flow_elements,
\ extend(copy(global_attributes), {'cite': []})
\ ],
\ 'body': [
\ flow_elements,
\ extend(copy(global_attributes), body_attributes)
\ ],
\ 'br': [
\ [],
\ global_attributes
\ ],
\ 'button': [
\ filter(copy(phrasing_elements), "!(v:val =~ '". abutton_dec ."')"),
\ extend(copy(global_attributes), {'type': ['submit', 'reset', 'button'], 'name': [], 'disabled': ['disabled', ''], 'form': [], 'value': [], 'formaction': [], 'autofocus': ['autofocus', ''], 'formenctype': ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain'], 'formmethod': ['get', 'post', 'put', 'delete'], 'formtarget': [], 'formnovalidate': ['formnovalidate', '']})
\ ],
\ 'canvas': [
\ flow_elements,
\ extend(copy(global_attributes), {'height': [], 'width': []})
\ ],
\ 'caption': [
\ filter(copy(flow_elements), "!(v:val =~ 'table')"),
\ global_attributes
\ ],
\ 'cite': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'code': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'col': [
\ [],
\ extend(copy(global_attributes), {'span': []})
\ ],
\ 'colgroup': [
\ [],
\ extend(copy(global_attributes), {'span': []})
\ ],
\ 'content': [
\ [],
\ extend(copy(global_attributes), {'select': []})
\ ],
\ 'command': [
\ ['col'],
\ extend(copy(global_attributes), {'type': ['command', 'radio', 'checkbox'], 'radiogroup': [], 'checked': ['checked', ''], 'label': [], 'icon': [], 'disabled': ['disabled', '']})
\ ],
\ 'datalist': [
\ phrasing_elements + ['option'],
\ global_attributes
\ ],
\ 'dd': [
\ flow_elements,
\ global_attributes
\ ],
\ 'del': [
\ flow_elements,
\ extend(copy(global_attributes), {'cite': [], 'datetime': []})
\ ],
\ 'details': [
\ flow_elements + ['summary'],
\ extend(copy(global_attributes), {'open': ['open', '']})
\ ],
\ 'dfn': [
\ filter(copy(phrasing_elements), "!(v:val =~ 'dfn')"),
\ global_attributes
\ ],
\ 'div': [
\ flow_elements + ['style'],
\ global_attributes
\ ],
\ 'dl': [
\ ['dt', 'dd'],
\ global_attributes
\ ],
\ 'dt': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'em': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'embed': [
\ [],
\ extend(copy(global_attributes), {'src': [], 'type': [], 'height': [], 'width': []})
\ ],
\ 'fieldset': [
\ flow_elements + ['legend'],
\ extend(copy(global_attributes), {'name': [], 'disabled': ['disabled', ''], 'form': []})
\ ],
\ 'figcaption': [
\ flow_elements,
\ global_attributes
\ ],
\ 'figure': [
\ flow_elements + ['figcaption'],
\ global_attributes
\ ],
\ 'footer': [
\ filter(copy(flow_elements), "!(v:val =~ 'address\\|header\\|footer')"),
\ global_attributes
\ ],
\ 'form': [
\ flow_elements,
\ extend(copy(global_attributes), {'name': [], 'action': [], 'enctype': ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain'], 'method': ['get', 'post', 'put', 'delete'], 'target': [], 'novalidate': ['novalidate', ''], 'accept-charset': charset, 'autocomplete': ['on', 'off']})
\ ],
\ 'h1': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'h2': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'h3': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'h4': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'h5': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'h6': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'head': [
\ metadata_elements + ['title', 'base'],
\ global_attributes
\ ],
\ 'header': [
\ filter(copy(flow_elements), "!(v:val =~ 'address\\|header\\|footer')"),
\ global_attributes
\ ],
\ 'hgroup': [
\ ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
\ global_attributes
\ ],
\ 'hr': [
\ [],
\ global_attributes
\ ],
\ 'html': [
\ ['head', 'body'],
\ extend(copy(global_attributes), {'manifest': [], 'version': ['HTML+RDFa 1.1']})
\ ],
\ 'i': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'iframe': [
\ [],
\ extend(copy(global_attributes), {'src': [], 'name': [], 'width': [], 'height': [], 'sandbox': ['allow-same-origin', 'allow-forms', 'allow-scripts'], 'seamless': ['seamless', '']})
\ ],
\ 'img': [
\ [],
\ extend(copy(global_attributes), {'src': [], 'alt': [], 'height': [], 'width': [], 'usemap': [], 'ismap': ['ismap', '']})
\ ],
\ 'input': [
\ [],
\ extend(copy(global_attributes), {'type': ['text', 'password', 'checkbox', 'radio', 'button', 'submit', 'reset', 'file', 'hidden', 'image', 'datetime', 'datetime-local', 'date', 'month', 'time', 'week', 'number', 'range', 'email', 'url', 'search', 'tel', 'coloe'], 'name': [], 'disabled': ['disabled', ''], 'form': [], 'maxlength': [], 'readonly': ['readonly', ''], 'size': [], 'value': [], 'autocomplete': ['on', 'off'], 'autofocus': ['autofocus', ''], 'list': [], 'pattern': [], 'required': ['required', ''], 'placeholder': [], 'checked': ['checked'], 'accept': [], 'multiple': ['multiple', ''], 'alt': [], 'src': [], 'height': [], 'width': [], 'min': [], 'max': [], 'step': [], 'formenctype': ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain'], 'formmethod': ['get', 'post', 'put', 'delete'], 'formtarget': [], 'formnovalidate': ['formnovalidate', '']})
\ ],
\ 'ins': [
\ flow_elements,
\ extend(copy(global_attributes), {'cite': [], 'datetime': []})
\ ],
\ 'kbd': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'keygen': [
\ [],
\ extend(copy(global_attributes), {'challenge': [], 'keytype': ['rsa'], 'autofocus': ['autofocus', ''], 'name': [], 'disabled': ['disabled', ''], 'form': []})
\ ],
\ 'label': [
\ filter(copy(phrasing_elements), "!(v:val =~ 'label')"),
\ extend(copy(global_attributes), {'for': [], 'form': []})
\ ],
\ 'legend': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'li': [
\ flow_elements,
\ extend(copy(global_attributes), {'value': []})
\ ],
\ 'link': [
\ [],
\ extend(copy(global_attributes), {'href': [], 'rel': linkreltypes, 'hreflang': lang_tag, 'media': [], 'type': [], 'sizes': ['any']})
\ ],
\ 'main': [
\ flow_elements + ['style'],
\ global_attributes
\ ],
\ 'map': [
\ flow_elements,
\ extend(copy(global_attributes), {'name': []})
\ ],
\ 'mark': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'menu': [
\ flow_elements + ['li'],
\ extend(copy(global_attributes), {'type': ['toolbar', 'context'], 'label': []})
\ ],
\ 'meta': [
\ [],
\ extend(copy(global_attributes), {'name': [], 'http-equiv': ['refresh', 'default-style', 'content-type'], 'content': [], 'charset': charset})
\ ],
\ 'meter': [
\ phrasing_elements,
\ extend(copy(global_attributes), {'value': [], 'min': [], 'low': [], 'high': [], 'max': [], 'optimum': []})
\ ],
\ 'nav': [
\ flow_elements,
\ global_attributes
\ ],
\ 'noscript': [
\ flow_elements + ['link', 'meta', 'style'],
\ global_attributes
\ ],
\ 'object': [
\ flow_elements + ['param'],
\ extend(copy(global_attributes), {'data': [], 'type': [], 'height': [], 'width': [], 'usemap': [], 'name': [], 'form': []})
\ ],
\ 'ol': [
\ ['li'],
\ extend(copy(global_attributes), {'start': [], 'reversed': ['reversed', '']})
\ ],
\ 'optgroup': [
\ ['option'],
\ extend(copy(global_attributes), {'label': [], 'disabled': ['disabled', '']})
\ ],
\ 'option': [
\ [''],
\ extend(copy(global_attributes), {'disabled': ['disabled', ''], 'selected': ['selected', ''], 'label': [], 'value': []})
\ ],
\ 'output': [
\ phrasing_elements,
\ extend(copy(global_attributes), {'name': [], 'form': [], 'for': []})
\ ],
\ 'p': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'param': [
\ [],
\ extend(copy(global_attributes), {'name': [], 'value': []})
\ ],
\ 'pre': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'progress': [
\ filter(copy(phrasing_elements), "!(v:val =~ 'progress')"),
\ extend(copy(global_attributes), {'value': [], 'max': []})
\ ],
\ 'q': [
\ phrasing_elements,
\ extend(copy(global_attributes), {'cite': []})
\ ],
\ 'rp': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'rt': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'ruby': [
\ phrasing_elements + ['rp', 'rt'],
\ global_attributes
\ ],
\ 'samp': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'script': [
\ [],
\ extend(copy(global_attributes), {'src': [], 'defer': ['defer', ''], 'async': ['async', ''], 'type': [], 'charset': charset})
\ ],
\ 'section': [
\ flow_elements + ['style'],
\ global_attributes
\ ],
\ 'select': [
\ ['optgroup', 'option'],
\ extend(copy(global_attributes), {'name': [], 'disabled': ['disabled', ''], 'form': [], 'size': [], 'multiple': ['multiple', '']})
\ ],
\ 'shadow': [
\ [],
\ global_attributes
\ ],
\ 'small': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'source': [
\ [],
\ extend(copy(global_attributes), {'src': [], 'type': [], 'media': []})
\ ],
\ 'span': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'strong': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'style': [
\ [],
\ extend(copy(global_attributes), {'type': [], 'media': [], 'scoped': ['scoped', '']})
\ ],
\ 'sub': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'summary': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'sup': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'table': [
\ ['caption', 'col', 'colgroup', 'thead', 'tfoot', 'tbody', 'tr'],
\ extend(copy(global_attributes), {'border': []})
\ ],
\ 'tbody': [
\ ['tr'],
\ global_attributes
\ ],
\ 'td': [
\ flow_elements,
\ extend(copy(global_attributes), {'colspan': [], 'rowspan': [], 'headers': []})
\ ],
\ 'template': [
\ flow_elements + ['style'],
\ global_attributes
\ ],
\ 'textarea': [
\ [''],
\ extend(copy(global_attributes), {'name': [], 'disabled': ['disabled', ''], 'form': [], 'readonly': ['readonly', ''], 'maxlength': [], 'autofocus': ['autofocus', ''], 'required': ['required', ''], 'placeholder': [], 'rows': [], 'wrap': ['hard', 'soft'], 'cols': []})
\ ],
\ 'tfoot': [
\ ['tr'],
\ global_attributes
\ ],
\ 'th': [
\ phrasing_elements,
\ extend(copy(global_attributes), {'scope': ['row', 'col', 'rowgroup', 'colgroup'], 'colspan': [], 'rowspan': [], 'headers': []})
\ ],
\ 'thead': [
\ ['tr'],
\ global_attributes
\ ],
\ 'time': [
\ phrasing_elements,
\ extend(copy(global_attributes), {'datetime': [], 'pubdate': ['pubdate', '']})
\ ],
\ 'data': [
\ phrasing_elements,
\ extend(copy(global_attributes), {'value': []})
\ ],
\ 'title': [
\ [''],
\ global_attributes
\ ],
\ 'tr': [
\ ['th', 'td'],
\ global_attributes
\ ],
\ 'track': [
\ [],
\ extend(copy(global_attributes), {'kind': ['subtitles', 'captions', 'descriptions', 'chapters', 'metadata'], 'src': [], 'charset': charset, 'srclang': lang_tag, 'label': []})
\ ],
\ 'u': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'ul': [
\ ['li'],
\ global_attributes
\ ],
\ 'var': [
\ phrasing_elements,
\ global_attributes
\ ],
\ 'video': [
\ flow_elements + ['source', 'track'],
\ extend(copy(global_attributes), {'autoplay': ['autoplay', ''], 'preload': ['none', 'metadata', 'auto', ''], 'controls': ['controls', ''], 'loop': ['loop', ''], 'poster': [], 'height': [], 'width': [], 'src': []})
\ ],
\ 'wbr': [
\ [],
\ global_attributes
\ ],
\ 'vimxmlattrinfo' : attributes_value,
\ 'vimxmltaginfo': {
\ 'area': ['/>', ''],
\ 'base': ['/>', ''],
\ 'br': ['/>', ''],
\ 'col': ['/>', ''],
\ 'command': ['/>', ''],
\ 'embed': ['/>', ''],
\ 'hr': ['/>', ''],
\ 'img': ['/>', ''],
\ 'input': ['/>', ''],
\ 'keygen': ['/>', ''],
\ 'link': ['/>', ''],
\ 'meta': ['/>', ''],
\ 'param': ['/>', ''],
\ 'source': ['/>', ''],
\ 'track': ['/>', ''],
\ 'wbr': ['/>', ''],
\ },
\ }

161
build
View File

@@ -1,88 +1,127 @@
#!/bin/sh
#!/usr/bin/env bash
set -E
DIRS="
syntax indent ftplugin ftdetect autoload compiler
after/syntax after/indent after/ftplugin after/ftdetect
"
copy_dir() {
if [ -d "$1/$2" ]; then
for file in $(find "$1/$2" -name '*.vim'); do
file_path="$(dirname "${file##$1/}")"
mkdir -p "$file_path"
cp $file $file_path/
done
fi
}
# Fetches syntax files from given Github repo
DIRS="syntax indent compiler autoload ftplugin ftdetect after/syntax after/indent after/ftplugin after/ftdetect"
download() {
for pack in $1; do
dir="tmp/$(echo "$pack" | cut -d '/' -f 2)"
echo "- [$pack](https://github.com/$pack)"
path="$(printf "$pack" | cut -d ':' -f 2)"
dir="tmp/$(printf "$path" | cut -d '/' -f 2)"
rm -rf "$dir"
git clone -q --recursive "https://github.com/$pack.git" "$dir" &
(git clone -q --recursive "https://github.com/$path.git" "$dir" && printf '.') &
done
wait
}
extract() {
printf "\n"
for pack in $1; do
dir="tmp/$(echo "$pack" | cut -d '/' -f 2)"
# which tree > /dev/null && tree tmp
name="$(printf "$pack" | cut -d ':' -f 1)"
path="$(printf "$pack" | cut -d ':' -f 2)"
dir="tmp/$(printf "$path" | cut -d '/' -f 2)"
printf -- "- [$name](https://github.com/$path) ("
subdirs=""
for subdir in $DIRS; do
copy_dir "$dir" "$subdir"
if [ -d "$dir/$subdir" ]; then
base="$(basename "$subdir")"
if [[ "$subdirs" != *"$base"* ]]; then
subdirs="$subdirs, $base"
fi
copy_dir "$dir" "$subdir"
fi
done
printf "${subdirs##, })\n"
done
for pack in $1; do
name="$(printf "$pack" | cut -d ':' -f 1)"
path="$(printf "$pack" | cut -d ':' -f 2)"
dir="tmp/$(printf "$path" | cut -d '/' -f 2)"
if [ -d "$dir/plugin" ]; then
printf "Possible error (plugin directory exists): $path\n"
fi
done
}
rm -rf tmp
rm -rf $DIRS
mkdir -p tmp
copy_dir() {
for file in $(find "$1/$2" -name '*.vim'); do
file_path="$(dirname "${file##$1/}")"
mkdir -p "$file_path"
touch "$file_path/$(basename "$file")"
cat $file >> $file_path/$(basename "$file")
done
}
concat_ftdetect() {
cat ftdetect/* | grep -E '^[^"]' > tmp/polyglot.vim
rm -f ftdetect/*
mv tmp/polyglot.vim ftdetect/
}
PACKS="
vim-ruby/vim-ruby
kchmck/vim-coffee-script
tpope/vim-haml
tpope/vim-bundler
pangloss/vim-javascript
leshill/vim-json
mutewinter/tomdoc.vim
mutewinter/nginx.vim
timcharper/textile.vim
tpope/vim-markdown
nono/vim-handlebars
acustodioo/vim-tmux
groenewege/vim-less
wavded/vim-stylus
tpope/vim-cucumber
jrk/vim-ocaml
slim-template/vim-slim
vim-scripts/XSLT-syntax
vim-scripts/python.vim--Vasiliev
vim-scripts/octave.vim--
jnwhiteh/vim-golang
spf13/PIV
briancollins/vim-jst
derekwyatt/vim-scala
derekwyatt/vim-sbt
travitch/hasksyn
ajf/puppet-vim
beyondwords/vim-twig
sudar/vim-arduino-syntax
guns/vim-clojure-static
chrisbra/csv.vim
elixir-lang/vim-elixir
jimenezrick/vimerl
tpope/vim-git
skwp/vim-rspec
arduino:sudar/vim-arduino-syntax
c++11:octol/vim-cpp-enhanced-highlight
c/c++:vim-jp/cpp-vim
clojure:guns/vim-clojure-static
coffee-script:kchmck/vim-coffee-script
csv:chrisbra/csv.vim
cucumber:tpope/vim-cucumber
dockerfile:honza/dockerfile.vim
elixir:elixir-lang/vim-elixir
erlang:oscarh/vimerl
git:tpope/vim-git
go:jnwhiteh/vim-golang
haml:tpope/vim-haml
handlebars:mustache/vim-mustache-handlebars
haskell:travitch/hasksyn
html5:othree/html5.vim
jade:digitaltoad/vim-jade
javascript:pangloss/vim-javascript
json:leshill/vim-json
jst:briancollins/vim-jst
latex:LaTeX-Box-Team/LaTeX-Box
less:groenewege/vim-less
markdown:tpope/vim-markdown
nginx:mutewinter/nginx.vim
ocaml:jrk/vim-ocaml
octave:vim-scripts/octave.vim--
perl:vim-perl/vim-perl
php:StanAngeloff/php.vim
puppet:ajf/puppet-vim
protobuf:uarun/vim-protobuf
python:vim-scripts/python.vim--Vasiliev
r-lang:vim-scripts/R.vim
rspec:sheerun/rspec.vim
ruby:vim-ruby/vim-ruby
rust:wting/rust.vim
sbt:derekwyatt/vim-sbt
scala:derekwyatt/vim-scala
slim:slim-template/vim-slim
stylus:wavded/vim-stylus
textile:timcharper/textile.vim
tmux:acustodioo/vim-tmux
tomdoc:duwanis/tomdoc.vim
typescript:leafgarland/typescript-vim
vbnet:vim-scripts/vbnet.vim
twig:beyondwords/vim-twig
xls:vim-scripts/XSLT-syntax
css-color:gorodinskiy/vim-coloresque
"
rm -rf tmp
rm -rf $DIRS
mkdir tmp
printf "Downloading packs..."
download "$PACKS"
extract "$PACKS"
concat_ftdetect
rm -rf tmp

View File

@@ -1,26 +0,0 @@
" Vim compiler file
if exists("current_compiler")
finish
endif
let current_compiler = "bundler"
let s:cpo_save = &cpo
set cpo-=C
CompilerSet makeprg=bundle
CompilerSet errorformat=
\%+E%f:%l:\ parse\ error,
\%W%f:%l:\ warning:\ %m,
\%E%f:%l:in\ %*[^:]:\ %m,
\%E%f:%l:\ %m,
\%-C%\tfrom\ %f:%l:in\ %.%#,
\%-Z%\tfrom\ %f:%l,
\%-Z%p^,
\%-G%.%#
let &cpo = s:cpo_save
unlet s:cpo_save
" vim: sw=2:

View File

@@ -27,8 +27,8 @@ function! s:GetMakePrg()
\ ' -c' .
\ ' ' . b:coffee_litcoffee .
\ ' ' . g:coffee_make_options .
\ ' ' . fnameescape(expand('%')) .
\ ' $*'
\ ' $*' .
\ ' ' . fnameescape(expand('%'))
endfunction
" Set `makeprg` and return 1 if coffee is still the compiler, else return 0.
@@ -75,8 +75,8 @@ augroup CoffeeUpdateMakePrg
" Set autocmd locally if compiler was set locally.
if &l:makeprg =~ s:pat
autocmd BufFilePost,BufWritePost <buffer> call s:UpdateMakePrg()
autocmd BufWritePre,BufFilePost <buffer> call s:UpdateMakePrg()
else
autocmd BufFilePost,BufWritePost call s:UpdateMakePrg()
autocmd BufWritePre,BufFilePost call s:UpdateMakePrg()
endif
augroup END

View File

@@ -1,111 +1,80 @@
" Vim compiler file
" Language: Erlang
" Author: Pawel 'kTT' Salata <rockplayer.pl@gmail.com>
" Contributors: Ricardo Catalinas Jiménez <jimenezrick@gmail.com>
" License: Vim license
" Version: 2013/03/06
" Erlang compiler file
" Language: Erlang
" Maintainer: Pawel 'kTT' Salata <rockplayer.pl@gmail.com>
" URL: http://ktototaki.info
if exists("current_compiler") || v:version < 703
finish
else
let current_compiler = "erlang"
if exists("current_compiler")
finish
endif
let b:error_list = {}
let b:is_showing_msg = 0
let b:next_sign_id = 1
let current_compiler = "erlang"
if exists(":CompilerSet") != 2
command -nargs=* CompilerSet setlocal <args>
command -nargs=* CompilerSet setlocal <args>
endif
CompilerSet makeprg=make
CompilerSet errorformat=%f:%l:\ %tarning:\ %m,%f:%l:\ %m
" Only define functions and script scope variables once
if exists("*s:ShowErrors")
finish
if !exists('g:erlangCheckFile')
let g:erlangCheckFile = "~/.vim/compiler/erlang_check_file.erl"
endif
if !exists("g:erlang_show_errors")
let g:erlang_show_errors = 1
if !exists('g:erlangHighlightErrors')
let g:erlangHighlightErrors = 0
endif
let s:erlang_check_file = expand("<sfile>:p:h") . "/erlang_check.erl"
let s:autocmds_defined = 0
let b:error_list = {}
let b:is_showing_msg = 0
sign define ErlangError text=>> texthl=Error
sign define ErlangWarning text=>> texthl=Todo
command ErlangDisableShowErrors silent call s:DisableShowErrors()
command ErlangEnableShowErrors silent call s:EnableShowErrors()
function s:ShowErrors()
setlocal shellpipe=>
if match(getline(1), "#!.*escript") != -1
setlocal makeprg=escript\ -s\ %
else
execute "setlocal makeprg=" . s:erlang_check_file . "\\ \%"
endif
silent make!
for error in getqflist()
let item = {}
let item["lnum"] = error.lnum
let item["text"] = error.text
let b:error_list[error.lnum] = item
let type = error.type == "W" ? "ErlangWarning" : "ErlangError"
execute "sign place" b:next_sign_id "line=" . item.lnum "name=" . type "file=" . expand("%:p")
let b:next_sign_id += 1
endfor
setlocal shellpipe&
setlocal makeprg=make
function! HighlightErlangErrors()
if match(getline(1), "#!.*escript") != -1
setlocal makeprg=escript\ -s\ %
else
execute "setlocal makeprg=" . g:erlangCheckFile . "\\ \%"
endif
silent make!
call s:clear_matches()
for error in getqflist()
let item = {}
let item['lnum'] = error.lnum
let item['msg'] = error.text
let b:error_list[error.lnum] = item
call matchadd('SpellBad', "\\%" . error.lnum . "l")
endfor
if len(getqflist())
redraw!
endif
call s:show_msg()
setlocal makeprg=erlc\ %
endfunction
function s:ShowErrorMsg()
let pos = getpos(".")
if has_key(b:error_list, pos[1])
let item = get(b:error_list, pos[1])
echo item.text
let b:is_showing_msg = 1
else
if b:is_showing_msg
echo
let b:is_showing_msg = 0
endif
endif
function! s:show_msg()
let pos = getpos(".")
if has_key(b:error_list, pos[1])
let item = get(b:error_list, pos[1])
echo item.msg
let b:is_showing_msg = 1
else
if exists("b:is_showing_msg") && b:is_showing_msg == 1
echo
let b:is_showing_msg = 0
endif
endif
endf
function s:ClearErrors()
sign unplace *
let b:error_list = {}
let b:next_sign_id = 1
if b:is_showing_msg
echo
let b:is_showing_msg = 0
endif
function! s:clear_matches()
call clearmatches()
let b:error_list = {}
if exists("b:is_showing_msg") && b:is_showing_msg == 1
echo
let b:is_showing_msg = 0
endif
endfunction
function s:EnableShowErrors()
if !s:autocmds_defined
augroup vimerl
autocmd!
autocmd BufWritePre *.erl call s:ClearErrors()
autocmd BufWritePost *.erl call s:ShowErrors()
autocmd CursorHold *.erl call s:ShowErrorMsg()
autocmd CursorMoved *.erl call s:ShowErrorMsg()
augroup END
let s:autocmds_defined = 1
endif
endfunction
CompilerSet makeprg=erlc\ %
CompilerSet errorformat=%f:%l:\ %tarning:\ %m,%E%f:%l:\ %m
function s:DisableShowErrors()
sign unplace *
augroup vimerl
autocmd!
augroup END
let s:autocmds_defined = 0
endfunction
if g:erlang_show_errors
call s:EnableShowErrors()
if g:erlangHighlightErrors
autocmd BufLeave *.erl call s:clear_matches()
autocmd BufEnter *.erl call s:clear_matches()
autocmd BufWritePost *.erl call HighlightErlangErrors()
autocmd CursorHold *.erl call s:show_msg()
autocmd CursorMoved *.erl call s:show_msg()
endif

30
compiler/go.vim Normal file
View File

@@ -0,0 +1,30 @@
" Copyright 2013 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" compiler/go.vim: Vim compiler file for Go.
if exists("current_compiler")
finish
endif
let current_compiler = "go"
if exists(":CompilerSet") != 2
command -nargs=* CompilerSet setlocal <args>
endif
let s:save_cpo = &cpo
set cpo-=C
CompilerSet makeprg=go\ build
CompilerSet errorformat=
\%-G#\ %.%#,
\%A%f:%l:%c:\ %m,
\%A%f:%l:\ %m,
\%C%*\\s%m,
\%-G%.%#
let &cpo = s:save_cpo
unlet s:save_cpo
" vim:ts=4:sw=4:et

33
compiler/rustc.vim Normal file
View File

@@ -0,0 +1,33 @@
" Vim compiler file
" Compiler: Rust Compiler
" Maintainer: Chris Morgan <me@chrismorgan.info>
" Latest Revision: 2013 Jul 12
if exists("current_compiler")
finish
endif
let current_compiler = "rustc"
let s:cpo_save = &cpo
set cpo&vim
if exists(":CompilerSet") != 2
command -nargs=* CompilerSet setlocal <args>
endif
if exists("g:rustc_makeprg_no_percent") && g:rustc_makeprg_no_percent == 1
CompilerSet makeprg=rustc
else
CompilerSet makeprg=rustc\ \%
endif
CompilerSet errorformat=
\%f:%l:%c:\ %t%*[^:]:\ %m,
\%f:%l:%c:\ %*\\d:%*\\d\ %t%*[^:]:\ %m,
\%-G%f:%l\ %s,
\%-G%*[\ ]^,
\%-G%*[\ ]^%*[~],
\%-G%*[\ ]...
let &cpo = s:cpo_save
unlet s:cpo_save

8
compiler/typescript.vim Normal file
View File

@@ -0,0 +1,8 @@
if exists("current_compiler")
finish
endif
let current_compiler = "typescript"
CompilerSet makeprg=tsc\ $*\ %
CompilerSet errorformat=%+A\ %#%f\ %#(%l\\\,%c):\ %m,%C%m

View File

@@ -1 +0,0 @@
au BufRead,BufNewFile *.ino,*.pde set filetype=arduino

View File

@@ -1 +0,0 @@
au BufNewFile,BufRead *.clj,*.cljs,*.edn setf clojure

View File

@@ -1,17 +0,0 @@
" Language: CoffeeScript
" Maintainer: Mick Koch <kchmck@gmail.com>
" URL: http://github.com/kchmck/vim-coffee-script
" License: WTFPL
autocmd BufNewFile,BufRead *.coffee set filetype=coffee
autocmd BufNewFile,BufRead *Cakefile set filetype=coffee
autocmd BufNewFile,BufRead *.coffeekup,*.ck set filetype=coffee
autocmd BufNewFile,BufRead *._coffee set filetype=coffee
function! s:DetectCoffee()
if getline(1) =~ '^#!.*\<coffee\>'
set filetype=coffee
endif
endfunction
autocmd BufNewFile,BufRead * call s:DetectCoffee()

View File

@@ -1,3 +0,0 @@
" Install Filetype detection for CSV files
au BufRead,BufNewFile *.csv,*.dat,*.tsv,*.tab set filetype=csv

View File

@@ -1,2 +0,0 @@
" Cucumber
autocmd BufNewFile,BufReadPost *.feature,*.story set filetype=cucumber

View File

@@ -1,2 +0,0 @@
au BufRead,BufNewFile *.ex,*.exs set filetype=elixir
au FileType elixir setl sw=2 sts=2 et iskeyword+=!,?

View File

@@ -1,20 +0,0 @@
" Git
autocmd BufNewFile,BufRead *.git/{,modules/**/}{COMMIT_EDIT,MERGE_}MSG set ft=gitcommit
autocmd BufNewFile,BufRead *.git/config,.gitconfig,.gitmodules set ft=gitconfig
autocmd BufNewFile,BufRead */.config/git/config set ft=gitconfig
autocmd BufNewFile,BufRead *.git/modules/**/config set ft=gitconfig
autocmd BufNewFile,BufRead git-rebase-todo set ft=gitrebase
autocmd BufNewFile,BufRead .msg.[0-9]*
\ if getline(1) =~ '^From.*# This line is ignored.$' |
\ set ft=gitsendemail |
\ endif
autocmd BufNewFile,BufRead *.git/**
\ if getline(1) =~ '^\x\{40\}\>\|^ref: ' |
\ set ft=git |
\ endif
" This logic really belongs in scripts.vim
autocmd BufNewFile,BufRead,StdinReadPost *
\ if getline(1) =~ '^\(commit\|tree\|object\) \x\{40\}\>\|^tag \S\+$' |
\ set ft=git |
\ endif

View File

@@ -1,23 +0,0 @@
" We take care to preserve the user's fileencodings and fileformats,
" because those settings are global (not buffer local), yet we want
" to override them for loading Go files, which are defined to be UTF-8.
let s:current_fileformats = ''
let s:current_fileencodings = ''
" define fileencodings to open as utf-8 encoding even if it's ascii.
function! s:gofiletype_pre()
let s:current_fileformats = &g:fileformats
let s:current_fileencodings = &g:fileencodings
set fileencodings=utf-8 fileformats=unix
setlocal filetype=go
endfunction
" restore fileencodings as others
function! s:gofiletype_post()
let &g:fileformats = s:current_fileformats
let &g:fileencodings = s:current_fileencodings
endfunction
au BufNewFile *.go setlocal filetype=go fileencoding=utf-8 fileformat=unix
au BufRead *.go call s:gofiletype_pre()
au BufReadPost *.go call s:gofiletype_post()

View File

@@ -1,3 +0,0 @@
autocmd BufNewFile,BufRead *.haml,*.hamlbars setf haml
autocmd BufNewFile,BufRead *.sass setf sass
autocmd BufNewFile,BufRead *.scss setf scss

View File

@@ -1,3 +0,0 @@
if has("autocmd")
au BufNewFile,BufRead *.{handlebars,hb,hbs,hbt}{,.erb} set ft=html syntax=handlebars | runtime! ftplugin/handlebars.vim ftplugin/handlebars*.vim ftplugin/handlebars/*.vim
endif

View File

@@ -1,11 +0,0 @@
au BufNewFile,BufRead *.js setf javascript
au BufNewFile,BufRead *.jsm setf javascript
au BufNewFile,BufRead *.json setf javascript
au BufNewFile,BufRead Jakefile setf javascript
fun! s:SelectJavascript()
if getline(1) =~# '^#!.*/bin/env\s\+node\>'
set ft=javascript
endif
endfun
au BufNewFile,BufRead * call s:SelectJavascript()

View File

@@ -1,8 +0,0 @@
autocmd BufNewFile,BufRead *.json set filetype=json
augroup json_autocmd
autocmd!
autocmd FileType json setlocal autoindent
autocmd FileType json setlocal formatoptions=tcq2l
autocmd FileType json setlocal foldmethod=syntax
augroup END

View File

@@ -1,3 +0,0 @@
au BufNewFile,BufRead *.ejs set filetype=jst
au BufNewFile,BufRead *.jst set filetype=jst
au BufNewFile,BufRead *.hamljs set filetype=jst

View File

@@ -1 +0,0 @@
autocmd BufNewFile,BufRead *.less setf less

View File

@@ -1,6 +0,0 @@
autocmd BufNewFile,BufRead *.markdown,*.md,*.mdown,*.mkd,*.mkdn
\ if &ft =~# '^\%(conf\|modula2\)$' |
\ set ft=markdown |
\ else |
\ setf markdown |
\ endif

View File

@@ -1 +0,0 @@
au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/*,*/nginx/vhosts.d/*,nginx.conf if &ft == '' | setfiletype nginx | endif

127
ftdetect/polyglot.vim Normal file
View File

@@ -0,0 +1,127 @@
au BufRead,BufNewFile *.ino,*.pde set filetype=arduino
autocmd BufNewFile,BufRead *.clj,*.cljs,*.edn setlocal filetype=clojure
autocmd BufNewFile,BufRead *.coffee set filetype=coffee
autocmd BufNewFile,BufRead *Cakefile set filetype=coffee
autocmd BufNewFile,BufRead *.coffeekup,*.ck set filetype=coffee
autocmd BufNewFile,BufRead *._coffee set filetype=coffee
function! s:DetectCoffee()
if getline(1) =~ '^#!.*\<coffee\>'
set filetype=coffee
endif
endfunction
autocmd BufNewFile,BufRead * call s:DetectCoffee()
au BufRead,BufNewFile *.csv,*.dat,*.tsv,*.tab set filetype=csv
autocmd BufNewFile,BufReadPost *.feature,*.story set filetype=cucumber
au BufNewFile,BufRead Dockerfile set filetype=dockerfile
au BufRead,BufNewFile *.ex,*.exs set filetype=elixir
au FileType elixir setl sw=2 sts=2 et iskeyword+=!,?
autocmd BufNewFile,BufRead *.git/{,modules/**/}{COMMIT_EDIT,MERGE_}MSG set ft=gitcommit
autocmd BufNewFile,BufRead *.git/config,.gitconfig,.gitmodules set ft=gitconfig
autocmd BufNewFile,BufRead */.config/git/config set ft=gitconfig
autocmd BufNewFile,BufRead *.git/modules/**/config set ft=gitconfig
autocmd BufNewFile,BufRead git-rebase-todo set ft=gitrebase
autocmd BufNewFile,BufRead .msg.[0-9]*
\ if getline(1) =~ '^From.*# This line is ignored.$' |
\ set ft=gitsendemail |
\ endif
autocmd BufNewFile,BufRead *.git/**
\ if getline(1) =~ '^\x\{40\}\>\|^ref: ' |
\ set ft=git |
\ endif
autocmd BufNewFile,BufRead,StdinReadPost *
\ if getline(1) =~ '^\(commit\|tree\|object\) \x\{40\}\>\|^tag \S\+$' |
\ set ft=git |
\ endif
let s:current_fileformats = ''
let s:current_fileencodings = ''
function! s:gofiletype_pre()
let s:current_fileformats = &g:fileformats
let s:current_fileencodings = &g:fileencodings
set fileencodings=utf-8 fileformats=unix
setlocal filetype=go
endfunction
function! s:gofiletype_post()
let &g:fileformats = s:current_fileformats
let &g:fileencodings = s:current_fileencodings
endfunction
au BufNewFile *.go setlocal filetype=go fileencoding=utf-8 fileformat=unix
au BufRead *.go call s:gofiletype_pre()
au BufReadPost *.go call s:gofiletype_post()
autocmd BufNewFile,BufRead *.haml,*.hamlbars setf haml
autocmd BufNewFile,BufRead *.sass setf sass
autocmd BufNewFile,BufRead *.scss setf scss
autocmd BufNewFile,BufReadPost *.jade set filetype=jade
au BufNewFile,BufRead *.js setf javascript
au BufNewFile,BufRead *.jsm setf javascript
au BufNewFile,BufRead Jakefile setf javascript
fun! s:SelectJavascript()
if getline(1) =~# '^#!.*/bin/env\s\+node\>'
set ft=javascript
endif
endfun
au BufNewFile,BufRead * call s:SelectJavascript()
autocmd BufNewFile,BufRead *.json set filetype=json
augroup json_autocmd
autocmd!
autocmd FileType json setlocal autoindent
autocmd FileType json setlocal formatoptions=tcq2l
autocmd FileType json setlocal foldmethod=syntax
augroup END
au BufNewFile,BufRead *.ejs set filetype=jst
au BufNewFile,BufRead *.jst set filetype=jst
au BufNewFile,BufRead *.hamljs set filetype=jst
autocmd BufNewFile,BufRead *.less setf less
autocmd BufNewFile,BufRead *.markdown,*.md,*.mdown,*.mkd,*.mkdn
\ if &ft =~# '^\%(conf\|modula2\)$' |
\ set ft=markdown |
\ else |
\ setf markdown |
\ endif
autocmd BufRead *.html
\ if getline(1) =~ '^\(%\|<[%&].*>\)' |
\ set filetype=mason |
\ endif
if has("autocmd")
au BufNewFile,BufRead *.mustache,*.handlebars,*.hbs,*.hogan,*.hulk,*.hjs set filetype=html syntax=mustache | runtime! ftplugin/mustache.vim ftplugin/mustache*.vim ftplugin/mustache/*.vim
endif
au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/*,*/nginx/vhosts.d/*,nginx.conf if &ft == '' | setfiletype nginx | endif
autocmd BufNewFile,BufRead *.proto setfiletype proto
au BufRead,BufNewFile *.pp set filetype=puppet
au BufNewFile,BufRead *.rb,*.rbw,*.gemspec set filetype=ruby
au BufNewFile,BufRead *.builder,*.rxml,*.rjs set filetype=ruby
au BufNewFile,BufRead [rR]akefile,*.rake set filetype=ruby
au BufNewFile,BufRead [rR]antfile,*.rant set filetype=ruby
au BufNewFile,BufRead .irbrc,irbrc set filetype=ruby
au BufNewFile,BufRead .pryrc set filetype=ruby
au BufNewFile,BufRead *.ru set filetype=ruby
au BufNewFile,BufRead Capfile set filetype=ruby
au BufNewFile,BufRead Gemfile set filetype=ruby
au BufNewFile,BufRead Guardfile,.Guardfile set filetype=ruby
au BufNewFile,BufRead Cheffile set filetype=ruby
au BufNewFile,BufRead Berksfile set filetype=ruby
au BufNewFile,BufRead [vV]agrantfile set filetype=ruby
au BufNewFile,BufRead .autotest set filetype=ruby
au BufNewFile,BufRead *.erb,*.rhtml set filetype=eruby
au BufNewFile,BufRead [tT]horfile,*.thor set filetype=ruby
au BufNewFile,BufRead *.rabl set filetype=ruby
au BufNewFile,BufRead *.jbuilder set filetype=ruby
au BufNewFile,BufRead Puppetfile set filetype=ruby
au BufNewFile,BufRead [Bb]uildfile set filetype=ruby
au BufNewFile,BufRead Appraisals set filetype=ruby
au BufRead,BufNewFile *.rs set filetype=rust
au BufRead,BufNewFile *.sbt set filetype=sbt
fun! s:DetectScala()
if getline(1) == '#!/usr/bin/env scala'
set filetype=scala
endif
endfun
au BufRead,BufNewFile *.scala,*.sbt set filetype=scala
au BufRead,BufNewFile * call s:DetectScala()
autocmd BufNewFile,BufRead *.slim set filetype=slim
autocmd BufNewFile,BufReadPost *.styl set filetype=stylus
autocmd BufNewFile,BufReadPost *.stylus set filetype=stylus
au BufRead,BufNewFile *.textile set filetype=textile
autocmd BufNewFile,BufRead .tmux.conf*,tmux.conf* setf tmux
autocmd BufNewFile,BufRead *.twig set filetype=twig
autocmd BufNewFile,BufRead *.html.twig set filetype=html.twig
autocmd BufNewFile,BufRead *.ts setlocal filetype=typescript

View File

@@ -1,2 +0,0 @@
" detect puppet filetype
au BufRead,BufNewFile *.pp set filetype=puppet

View File

@@ -1,62 +0,0 @@
" Ruby
au BufNewFile,BufRead *.rb,*.rbw,*.gemspec set filetype=ruby
" Ruby on Rails
au BufNewFile,BufRead *.builder,*.rxml,*.rjs set filetype=ruby
" Rakefile
au BufNewFile,BufRead [rR]akefile,*.rake set filetype=ruby
" Rantfile
au BufNewFile,BufRead [rR]antfile,*.rant set filetype=ruby
" IRB config
au BufNewFile,BufRead .irbrc,irbrc set filetype=ruby
" Pry config
au BufNewFile,BufRead .pryrc set filetype=ruby
" Rackup
au BufNewFile,BufRead *.ru set filetype=ruby
" Capistrano
au BufNewFile,BufRead Capfile set filetype=ruby
" Bundler
au BufNewFile,BufRead Gemfile set filetype=ruby
" Guard
au BufNewFile,BufRead Guardfile,.Guardfile set filetype=ruby
" Chef
au BufNewFile,BufRead Cheffile set filetype=ruby
au BufNewFile,BufRead Berksfile set filetype=ruby
" Vagrant
au BufNewFile,BufRead [vV]agrantfile set filetype=ruby
" Autotest
au BufNewFile,BufRead .autotest set filetype=ruby
" eRuby
au BufNewFile,BufRead *.erb,*.rhtml set filetype=eruby
" Thor
au BufNewFile,BufRead [tT]horfile,*.thor set filetype=ruby
" Rabl
au BufNewFile,BufRead *.rabl set filetype=ruby
" Jbuilder
au BufNewFile,BufRead *.jbuilder set filetype=ruby
" Puppet librarian
au BufNewFile,BufRead Puppetfile set filetype=ruby
"
" Buildr Buildfile
au BufNewFile,BufRead [Bb]uildfile set filetype=ruby
" Appraisal
au BufNewFile,BufRead Appraisals set filetype=ruby
" vim: nowrap sw=2 sts=2 ts=8 noet:

View File

@@ -1,6 +0,0 @@
" Vim detect file
" Language: sbt
" Maintainer: Derek Wyatt <derek@{myfirstname}{mylastname}.org>
" Last Change: 2012 Jan 19
au BufRead,BufNewFile *.sbt set filetype=sbt

View File

@@ -1,8 +0,0 @@
fun! s:DetectScala()
if getline(1) == '#!/usr/bin/env scala'
set filetype=scala
endif
endfun
au BufRead,BufNewFile *.scala,*.sbt set filetype=scala
au BufRead,BufNewFile * call s:DetectScala()

View File

@@ -1 +0,0 @@
autocmd BufNewFile,BufRead *.slim setf slim

View File

@@ -1,3 +0,0 @@
" Stylus
autocmd BufNewFile,BufReadPost *.styl set filetype=stylus
autocmd BufNewFile,BufReadPost *.stylus set filetype=stylus

View File

@@ -1,8 +0,0 @@
" textile.vim
"
" Tim Harper (tim.theenchanter.com)
" Force filetype to be textile even if already set
" This will override the system ftplugin/changelog
" set on some distros
au BufRead,BufNewFile *.textile set filetype=textile

View File

@@ -1 +0,0 @@
autocmd BufNewFile,BufRead .tmux.conf*,tmux.conf* setf tmux

View File

@@ -1,5 +0,0 @@
" Twig
autocmd BufNewFile,BufRead *.twig set filetype=twig
" HTML Twig
autocmd BufNewFile,BufRead *.html.twig set filetype=html.twig

View File

@@ -23,9 +23,8 @@ setlocal iskeyword+=?,-,*,!,+,/,=,<,>,.,:,$
" of user-defined def* definitions.
setlocal define=\\v[(/]def(ault)@!\\S*
" Remove 't' from 'formatoptions' to avoid auto-wrapping code. The '+=croql'
" is standard ftplugin boilerplate, although it is arguably intrusive.
setlocal formatoptions-=t formatoptions+=croql
" Remove 't' from 'formatoptions' to avoid auto-wrapping code.
setlocal formatoptions-=t
" Lisp comments are routinely nested (e.g. ;;; SECTION HEADING)
setlocal comments=n:;

View File

@@ -11,10 +11,10 @@
" though, implementation differs.
" Plugin folklore "{{{2
if v:version < 700 || exists('b:did_ftplugin')
if v:version < 700 || exists('b:did_csv_ftplugin')
finish
endif
let b:did_ftplugin = 1
let b:did_csv_ftplugin = 1
let s:cpo_save = &cpo
set cpo&vim
@@ -136,7 +136,8 @@ fu! <sid>Init(startline, endline) "{{{3
\ . "| unlet! b:csv_fixed_width b:csv_list b:col_width"
\ . "| unlet! b:csv_SplitWindow b:csv_headerline"
\ . "| unlet! b:csv_thousands_sep b:csv_decimal_sep"
\. " | unlet! b:browsefilter b:csv_start b:csv_end"
\. " | unlet! b:browsefilter b:csv_cmt"
\. " | unlet! b:csv_arrange_leftalign"
" Delete all functions
" disabled currently, because otherwise when switching ft
@@ -168,6 +169,7 @@ fu! <sid>Init(startline, endline) "{{{3
" \ delf <sid>SaveOptions | delf <sid>CheckDuplicates |
" \ delf <sid>CompleteColumnNr | delf <sid>CSVPat | delf <sid>Transpose |
" \ delf <sid>LocalSettings() | delf <sid>AddColumn | delf <sid>SubstituteInColumn
" \ delf <sid>SetupQuitPre() | delf CSV_CloseBuffer
endfu
fu! <sid>LocalSettings(type) "{{{3
@@ -275,7 +277,9 @@ fu! <sid>DoAutoCommands() "{{{3
au BufNewFile,BufNew * call <sid>Menu(0)
augroup END
"let b:undo_ftplugin .= '| sil! amenu disable CSV'
let b:undo_ftplugin .= '| sil! call <sid>Menu(0)'
"
" b:undo_ftplugin does not support calling <sid> Functions
"let b:undo_ftplugin .= '| sil! call <sid>Menu(0)'
endif
endfu
@@ -658,7 +662,7 @@ fu! <sid>ArrangeCol(first, last, bang) range "{{{3
else
let ro = 0
endif
exe a:first . ',' . a:last .'s/' . (b:col) .
exe "sil". a:first . ',' . a:last .'s/' . (b:col) .
\ '/\=<SID>Columnize(submatch(0))/' . (&gd ? '' : 'g')
" Clean up variables, that were only needed for <sid>Columnize() function
unlet! s:columnize_count s:max_cols s:prev_line
@@ -693,7 +697,11 @@ endfu
fu! <sid>UnArrangeCol(match) "{{{3
" Strip leading white space, also trims empty records:
return substitute(a:match, '^\s\+', '', '')
if get(b:, 'csv_arrange_leftalign',0)
return substitute(a:match, '\s\+\ze'. b:delimiter. '\?$', '', '')
else
return substitute(a:match, '^\s\+', '', '')
endif
" only strip leading white space, if a non-white space follows:
"return substitute(a:match, '^\s\+\ze\S', '', '')
endfu
@@ -741,9 +749,18 @@ fu! <sid>Columnize(field) "{{{3
let width=get(b:col_width, (s:columnize_count % s:max_cols), 20)
let s:columnize_count += 1
let has_delimiter = (a:field =~# b:delimiter.'$')
if v:version > 703 || v:version == 703 && has("patch713")
" printf knows about %S (e.g. can handle char length
return printf("%*S", width+1 , a:field)
if get(b:, 'csv_arrange_leftalign',0)
" left-align content
return printf("%-*S%s", width+1 ,
\ (has_delimiter ?
\ matchstr(a:field, '.*\%('.b:delimiter.'\)\@=') : a:field),
\ (has_delimiter ? b:delimiter : ''))
else
return printf("%*S", width+1 , a:field)
endif
else
" printf only handles bytes
if !exists("g:csv_no_multibyte") &&
@@ -765,7 +782,14 @@ fu! <sid>Columnize(field) "{{{3
" Column has correct length, don't use printf()
return a:field
else
return printf("%*s", width , a:field)
if get(b:, 'csv_arrange_leftalign',0)
" left-align content
return printf("%-*s%s", width,
\ (has_delimiter ? matchstr(a:field, '.*\%('.b:delimiter.'\)\@=') : a:field),
\ (has_delimiter ? b:delimiter : ''))
else
return printf("%*s", width , a:field)
endif
endif
endif
endfun
@@ -795,16 +819,13 @@ fu! <sid>GetColPat(colnr, zs_flag) "{{{3
return pat . (a:zs_flag ? '\zs' : '')
endfu
fu! <sid>SetupQuitPre() "{{{3
fu! <sid>SetupQuitPre(window) "{{{3
" Setup QuitPre autocommand to quit cleanly
if exists("##QuitPre")
let bufnr=bufnr('')
noa wincmd p
augroup CSV_QuitPre
au!
exe "au QuitPre * ". bufnr. "bw"
exe "au QuitPre * call CSV_CloseBuffer(".winbufnr(a:window).")"
augroup end
noa wincmd p
endif
endfu
@@ -839,7 +860,7 @@ fu! <sid>SplitHeaderLine(lines, bang, hor) "{{{3
"let b:col=b
"setl syntax=csv
sil! doautocmd FileType csv
1
noa 1
exe "resize" . lines
setl scrollopt=hor winfixheight nowrap
"let &l:stl=repeat(' ', winwidth(0))
@@ -848,31 +869,31 @@ fu! <sid>SplitHeaderLine(lines, bang, hor) "{{{3
let &l:fdc = _fdc
else
setl scrollopt=ver scrollbind
0
let a=<sid>CopyCol('',1)
" Force recalculating columns width
unlet! b:csv_list
try
let width = <sid>ColWidth(1)
catch /ColWidth/
call <sid>Warn("Error: getting Column Width, using default!")
endtry
noa 0
let a=<sid>CopyCol('',1,a:lines)
" Does it make sense to use the preview window?
"vert sil! pedit |wincmd w | enew!
above vsp +enew
call append(0, a)
$d _
sil %s/.*/\=printf("%.*s", width, submatch(0))/eg
0
exe "vert res" width
let b:col=b
let b:col = b
sil! doautocmd FileType csv
" remove leading delimiter
exe "sil :%s/^". b:delimiter. "//e"
" remove trailing delimiter
exe "sil :%s/". b:delimiter. "\s*$//e"
syn clear
noa 0
let b:csv_SplitWindow = winnr()
sil :call <sid>ArrangeCol(1,line('$'), 1)
exe "vert res" . len(split(getline(1), '\zs'))
call matchadd("CSVHeaderLine", b:col)
setl scrollopt=ver winfixwidth
endif
call <sid>SetupQuitPre()
call <sid>SetupQuitPre(winnr())
let win = winnr()
setl scrollbind buftype=nowrite bufhidden=wipe noswapfile nobuflisted
wincmd p
noa wincmd p
let b:csv_SplitWindow = win
aug CSV_Preview
au!
@@ -891,7 +912,12 @@ fu! <sid>SplitHeaderLine(lines, bang, hor) "{{{3
let &sbo = _sbo
endif
setl noscrollbind
wincmd c
try
wincmd c
catch /^Vim\%((\a\+)\)\=:E444/ " cannot close last window
catch /^Vim\%((\a\+)\)\=:E517/ " buffer already wiped
" no-op
endtry
"pclose!
unlet! b:csv_SplitWindow
aug CSV_Preview
@@ -910,8 +936,11 @@ fu! <sid>SplitHeaderToggle(hor) "{{{3
endfu
" TODO: from here on add logic for fixed-width csv files!
fu! <sid>MoveCol(forward, line) "{{{3
fu! <sid>MoveCol(forward, line, ...) "{{{3
" Move cursor position upwards/downwards left/right
" a:1 is there to have some mappings move in the same
" direction but still stop at a different position
" see :h csv-mapping-H
let colnr=<SID>WColumn()
let maxcol=<SID>MaxColumns()
let cpos=getpos('.')[2]
@@ -982,6 +1011,17 @@ fu! <sid>MoveCol(forward, line) "{{{3
norm! 0
endif
endw
if (exists("a:1") && a:1)
" H also stops at the beginning of the content
" of a field.
let epos = getpos('.')
if getline('.')[col('.')-1] == ' '
call search('\S', 'W', line('.'))
if getpos('.')[2] > spos
call setpos('.', epos)
endif
endif
endif
else
norm! 0
endif
@@ -1043,13 +1083,19 @@ fu! <sid>Sort(bang, line1, line2, colnr) range "{{{3
call winrestview(wsv)
endfun
fu! <sid>CopyCol(reg, col) "{{{3
fu! <sid>CopyCol(reg, col, cnt) "{{{3
" Return Specified Column into register reg
let col = a:col == "0" ? <sid>WColumn() : a:col+0
let mcol = <sid>MaxColumns()
if col == '$' || col > mcol
let col = mcol
endif
" The number of columns to return
" by default (value of zero, will only return that specific column)
let cnt_cols = col - 1
if !empty(a:cnt) && a:cnt > 0 && col + a:cnt <= mcol
let cnt_cols = col + a:cnt - 1
endif
let a = []
" Don't get lines, that are currently filtered away
if !exists("b:csv_filter") || empty(b:csv_filter)
@@ -1068,9 +1114,12 @@ fu! <sid>CopyCol(reg, col) "{{{3
call filter(a, 'v:val !~ pat')
if !exists("b:csv_fixed_width_cols")
call map(a, 'split(v:val, ''^'' . b:col . ''\zs'')[col-1]')
call map(a, 'split(v:val, ''^'' . b:col . ''\zs'')[col-1:cnt_cols]')
else
call map(a, 'matchstr(v:val, <sid>GetColPat(col, 0))')
call map(a, 'matchstr(v:val, <sid>GetColPat(col, 0)).*<sid>GetColPat(col+cnt_cols, 0)')
endif
if type(a[0]) == type([])
call map(a, 'join(v:val, "")')
endif
if a:reg =~ '[-"0-9a-zA-Z*+]'
"exe ':let @' . a:reg . ' = "' . join(a, "\n") . '"'
@@ -1222,8 +1271,8 @@ fu! <sid>SumColumn(list) "{{{3
if empty(item)
continue
endif
let nr = matchstr(item, '\d\(.*\d\)\?$')
let format1 = '^\d\+\zs\V' . s:nr_format[0] . '\m\ze\d'
let nr = matchstr(item, '-\?\d\(.*\d\)\?$')
let format1 = '^-\?\d\+\zs\V' . s:nr_format[0] . '\m\ze\d'
let format2 = '\d\+\zs\V' . s:nr_format[1] . '\m\ze\d'
try
let nr = substitute(nr, format1, '', '')
@@ -1574,10 +1623,13 @@ fu! <sid>AnalyzeColumn(...) "{{{3
" Initialize s:fold_headerline
call <sid>CheckHeaderLine()
let data = <sid>CopyCol('', colnr)[s:csv_fold_headerline : -1]
let data = <sid>CopyCol('', colnr, '')[s:csv_fold_headerline : -1]
let qty = len(data)
let res = {}
for item in data
if empty(item)
let item = 'NULL'
endif
if !get(res, item)
let res[item] = 0
endif
@@ -1585,6 +1637,7 @@ fu! <sid>AnalyzeColumn(...) "{{{3
endfor
let max_items = reverse(sort(values(res)))
let count_items = keys(res)
if len(max_items) > 5
call remove(max_items, 5, -1)
call filter(res, 'v:val =~ ''^''.join(max_items, ''\|'').''$''')
@@ -1595,9 +1648,9 @@ fu! <sid>AnalyzeColumn(...) "{{{3
else
let title="Nr\tCount\tValue"
endif
echohl "Title"
echohl Title
echo printf("%s", title)
echohl "Normal"
echohl Normal
echo printf("%s", repeat('=', strdisplaywidth(title)))
let i=1
@@ -1622,6 +1675,8 @@ fu! <sid>AnalyzeColumn(...) "{{{3
endif
endfor
endfor
echo printf("%s", repeat('=', strdisplaywidth(title)))
echo printf("different values: %d", len(count_items))
unlet max_items
endfunc
@@ -1665,59 +1720,56 @@ fu! <sid>InitCSVFixedWidth() "{{{3
endif
" Turn off syntax highlighting
syn clear
let max_len = len(split(getline(1), '\zs'))
let _cc = &l:cc
let &l:cc = 1
redraw!
let list = []
let Dict = {'1': 1} " first column is always the start of a new column
let tcc = &l:cc
let &l:cc = 1
echo "<Cursor>, <Space>, <ESC>, <BS>, <CR>..."
let char=getchar()
while 1
if char == "\<Left>" || char == "\<Right>"
let tcc = eval('tcc'.(char=="\<Left>" ? '-' : '+').'1')
if tcc < 0
let tcc=0
elseif tcc > max_len
let tcc = max_len
endif
elseif char == "\<Space>" || char == 32 " Space
call add(list, tcc)
let Dict[tcc] = 1
elseif char == "\<BS>" || char == 127
call remove(list, -1)
try
call remove(Dict, reverse(sort(keys(Dict)))[0])
catch /^Vim\%((\a\+)\)\=:E\(\%(716\)\|\%(684\)\)/ " Dict or List empty
break
endtry
elseif char == "\<ESC>" || char == 27
let &l:cc=_cc
redraw!
return
elseif char == "\<CR>" || char == "\n" || char == "\r" " Enter
let Dict[tcc] = 1
break
else
break
endif
let &l:cc=tcc . (!empty(list)? ',' . join(list, ','):'')
let &l:cc=tcc . (!empty(keys(Dict))? ',' . join(keys(Dict), ','):'')
redraw!
echo "<Cursor>, <Space>, <ESC>, <BS>, <CR>..."
let char=getchar()
endw
if tcc > 0
call add(list,tcc)
endif
let b:csv_fixed_width_cols=[]
let tcc=0
if !empty(list)
call Break()
" Remove duplicate entries
for val in sort(list, "<sid>SortList")
if val==tcc
continue
endif
call add(b:csv_fixed_width_cols, val)
let tcc=val
endfor
let b:csv_fixed_width=join(sort(b:csv_fixed_width_cols,
\ "<sid>SortList"), ',')
call <sid>Init(1, line('$'))
endif
let b:csv_fixed_width_cols = sort(keys(Dict), "<sid>SortList")
let b:csv_fixed_width = join(sort(keys(Dict), "<sid>SortList"), ',')
call <sid>Init(1, line('$'))
let &l:cc=_cc
redraw!
endfu
fu! Break()
return
endfu
fu! <sid>NewRecord(line1, line2, count) "{{{3
if a:count =~ "\D"
call <sid>WarningMsg("Invalid count specified")
@@ -1757,33 +1809,53 @@ fu! <sid>MoveOver(outer) "{{{3
" Move over a field
" a:outer means include the delimiter
let last = 0
let mode = a:outer
let outer_field = a:outer
let cur_field = <sid>WColumn()
let _wsv = winsaveview()
if <sid>WColumn() == <sid>MaxColumns()
if cur_field == <sid>MaxColumns()
let last = 1
if !mode && getline('.')[-1:] != b:delimiter
if !outer_field && getline('.')[-1:] != b:delimiter
" No trailing delimiter, so inner == outer
let mode = 1
let outer_field = 1
endif
endif
" Use the mapped key
exe ":sil! norm E"
" Move 1 column backwards, unless the cursor is in the first column
" or in front of a delimiter
if matchstr(getline('.'), '.\%'.virtcol('.').'v') != b:delimiter && virtcol('.') > 1
call <sid>MoveCol(-1, line('.'))
endif
" if cur_field != <sid>WColumn()
" cursor was at the beginning of the field, and moved back to the
" previous field, move back to original position
" call cursor(_wsv.lnum, _wsv.col)
" endif
let _s = @/
if last
exe "sil! norm! /" . b:col . "\<cr>v$h" . (mode ? "" : "\<Left>")
exe "sil! norm! v$h" . (outer_field ? "" : "h") . (&sel ==# 'exclusive' ? "l" : '')
else
exe "sil! norm! /" . b:col . "\<cr>vn\<Left>" . (mode ? "" : "\<Left>")
exe "sil! norm! v/." . b:col . "\<cr>h" . (outer_field ? "" : "h") . (&sel ==# 'exclusive' ? "l" : '')
endif
let _wsv.col = col('.')-1
call winrestview(_wsv)
let @/ = _s
endfu
fu! <sid>CSVMappings() "{{{3
call <sid>Map('noremap', 'W', ':<C-U>call <SID>MoveCol(1, line("."))<CR>')
call <sid>Map('noremap', '<C-Right>', ':<C-U>call <SID>MoveCol(1, line("."))<CR>')
call <sid>Map('noremap', 'L', ':<C-U>call <SID>MoveCol(1, line("."))<CR>')
call <sid>Map('noremap', 'E', ':<C-U>call <SID>MoveCol(-1, line("."))<CR>')
call <sid>Map('noremap', '<C-Left>', ':<C-U>call <SID>MoveCol(-1, line("."))<CR>')
call <sid>Map('noremap', 'H', ':<C-U>call <SID>MoveCol(-1, line("."), 1)<CR>')
call <sid>Map('noremap', 'K', ':<C-U>call <SID>MoveCol(0,
\ line(".")-v:count1)<CR>')
call <sid>Map('noremap', '<Up>', ':<C-U>call <SID>MoveCol(0,
\ line(".")-v:count1)<CR>')
call <sid>Map('noremap', 'J', ':<C-U>call <SID>MoveCol(0,
\ line(".")+v:count1)<CR>')
call <sid>Map('noremap', '<Down>', ':<C-U>call <SID>MoveCol(0,
\ line(".")+v:count1)<CR>')
call <sid>Map('nnoremap', '<CR>', ':<C-U>call <SID>PrepareFolding(1,
\ 1)<CR>')
call <sid>Map('nnoremap', '<Space>', ':<C-U>call <SID>PrepareFolding(1,
@@ -1806,12 +1878,6 @@ fu! <sid>CSVMappings() "{{{3
call <sid>Map('nnoremap', '<LocalLeader><CR>', '<CR>')
call <sid>Map('nnoremap', '<LocalLeader><Space>', '<Space>')
call <sid>Map('nnoremap', '<LocalLeader><BS>', '<BS>')
call <sid>Map('map', '<C-Right>', 'W')
call <sid>Map('map', '<C-Left>', 'E')
call <sid>Map('map', 'H', 'E')
call <sid>Map('map', 'L', 'W')
call <sid>Map('map', '<Up>', 'K')
call <sid>Map('map', '<Down>', 'J')
endfu
fu! <sid>CommandDefinitions() "{{{3
@@ -1845,8 +1911,8 @@ fu! <sid>CommandDefinitions() "{{{3
\ ':call <sid>Sort(<bang>0, <line1>,<line2>,<q-args>)',
\ '-nargs=* -bang -range=% -complete=custom,<sid>SortComplete')
call <sid>LocalCmd("Column",
\ ':call <sid>CopyCol(empty(<q-reg>)?''"'':<q-reg>,<q-count>)',
\ '-count -register')
\ ':call <sid>CopyCol(empty(<q-reg>)?''"'':<q-reg>,<q-count>,<q-args>)',
\ '-count -register -nargs=?')
call <sid>LocalCmd("MoveColumn",
\ ':call <sid>MoveColumn(<line1>,<line2>,<f-args>)',
\ '-range=% -nargs=* -complete=custom,<sid>SortComplete')
@@ -2327,15 +2393,20 @@ endfu
" Global functions "{{{2
fu! csv#EvalColumn(nr, func, first, last) range "{{{3
" Make sure, the function is called for the correct filetype.
if match(split(&ft, '\.'), 'csv') == -1
call <sid>Warn("File is no CSV file!")
return
endif
let save = winsaveview()
call <sid>CheckHeaderLine()
let nr = matchstr(a:nr, '^\d\+')
let nr = matchstr(a:nr, '^\-\?\d\+')
let col = (empty(nr) ? <sid>WColumn() : nr)
" don't take the header line into consideration
let start = a:first - 1 + s:csv_fold_headerline
let stop = a:last - 1 + s:csv_fold_headerline
let column = <sid>CopyCol('', col)[start : stop]
let column = <sid>CopyCol('', col, '')[start : stop]
" Delete delimiter
call map(column, 'substitute(v:val, b:delimiter . "$", "", "g")')
" Revmoe trailing whitespace
@@ -2395,7 +2466,7 @@ fu! CSVField(x, y, ...) "{{{3
let orig = !empty(a:0)
let y = (y < 0 ? 0 : y)
let x = (x > (<sid>MaxColumns()) ? (<sid>MaxColumns()) : x)
let col = <sid>CopyCol('',x)
let col = <sid>CopyCol('',x,'')
if !orig
" remove leading and trainling whitespace and the delimiter
return matchstr(col[y], '^\s*\zs.\{-}\ze\s*'.b:delimiter.'\?$')
@@ -2434,6 +2505,23 @@ fu! CSV_WCol(...) "{{{3
endtry
endfun
fu! CSV_CloseBuffer(buffer) "{{{3
" Setup by SetupQuitPre autocommand
try
if bufnr((a:buffer)+0) > -1
exe a:buffer. "bw"
endif
catch /^Vim\%((\a\+)\)\=:E517/ " buffer already wiped
" no-op
finally
augroup CSV_QuitPre
au!
augroup END
augroup! CSV_QuitPre
endtry
endfu
" Initialize Plugin "{{{2
let b:csv_start = exists("b:csv_start") ? b:csv_start : 1
let b:csv_end = exists("b:csv_end") ? b:csv_end : line('$')

View File

@@ -1,85 +1,151 @@
" Vim ftplugin file
" Language: Erlang
" Author: Oscar Hellström <oscar@oscarh.net>
" Contributors: Ricardo Catalinas Jiménez <jimenezrick@gmail.com>
" Eduardo Lopez (http://github.com/tapichu)
" License: Vim license
" Version: 2012/11/25
if exists('b:did_ftplugin')
" Language: Erlang
" Maintainer: Oscar Hellström <oscar@oscarh.net>
" URL: http://personal.oscarh.net
" Contributor: Ricardo Catalinas Jiménez <jimenezrick@gmail.com>
" Version: 2010-09-03
" ------------------------------------------------------------------------------
" Usage:
"
" To enable folding put in your vimrc:
" set foldenable
"
" Folding will make only one fold for a complete function, even though it has
" more than one function head and body.
"
" To change this behaviour put in your vimrc file:
" let g:erlangFoldSplitFunction=1
"
" ------------------------------------------------------------------------------
" Plugin init
if exists("b:did_ftplugin")
finish
else
let b:did_ftplugin = 1
endif
if exists('s:did_function_definitions')
" Don't load any other
let b:did_ftplugin=1
if exists('s:doneFunctionDefinitions')
call s:SetErlangOptions()
finish
else
let s:did_function_definitions = 1
endif
if !exists('g:erlang_keywordprg')
let g:erlang_keywordprg = 'erl -man'
endif
if !exists('g:erlang_folding')
let g:erlang_folding = 0
endif
let s:erlang_fun_begin = '^\(\a\w*\|[''][^'']*['']\)(.*$'
let s:erlang_fun_end = '^[^%]*\.\s*\(%.*\)\?$'
let s:doneFunctionDefinitions=1
" Local settings
function s:SetErlangOptions()
compiler erlang
if version >= 700
setlocal omnifunc=erlang_complete#Complete
setlocal omnifunc=erlangcomplete#Complete
endif
if g:erlang_folding
setlocal foldmethod=expr
setlocal foldexpr=GetErlangFold(v:lnum)
setlocal foldtext=ErlangFoldText()
endif
setlocal comments=:%%%,:%%,:%
setlocal commentstring=%%s
setlocal formatoptions+=ro
setlocal suffixesadd=.erl
let libs = substitute(system('which erl'), '/bin/erl', '/lib/erlang/lib/**/src/', '')
execute 'setlocal path+=' . libs
let &l:keywordprg = g:erlang_keywordprg
setlocal foldmethod=expr
setlocal foldexpr=GetErlangFold(v:lnum)
setlocal foldtext=ErlangFoldText()
endfunction
function GetErlangFold(lnum)
let lnum = a:lnum
let line = getline(lnum)
" Define folding functions
if !exists("*GetErlangFold")
" Folding params
let s:ErlangFunBegin = '^\a\w*(.*$'
let s:ErlangFunEnd = '^[^%]*\.\s*\(%.*\)\?$'
let s:ErlangBlankLine = '^\s*\(%.*\)\?$'
if line =~ s:erlang_fun_end
return '<1'
endif
" Auxiliary fold functions
function s:GetNextNonBlank(lnum)
let lnum = nextnonblank(a:lnum + 1)
let line = getline(lnum)
while line =~ s:ErlangBlankLine && 0 != lnum
let lnum = nextnonblank(lnum + 1)
let line = getline(lnum)
endwhile
return lnum
endfunction
if line =~ s:erlang_fun_begin && foldlevel(lnum - 1) == 1
return '1'
endif
function s:GetFunName(str)
return matchstr(a:str, '^\a\w*(\@=')
endfunction
if line =~ s:erlang_fun_begin
return '>1'
endif
function s:GetFunArgs(str, lnum)
let str = a:str
let lnum = a:lnum
while str !~ '->\s*\(%.*\)\?$'
let lnum = s:GetNextNonBlank(lnum)
if 0 == lnum " EOF
return ""
endif
let str .= getline(lnum)
endwhile
return matchstr(str,
\ '\(^(\s*\)\@<=.*\(\s*)\(\s\+when\s\+.*\)\?\s\+->\s*\(%.*\)\?$\)\@=')
endfunction
return '='
endfunction
function s:CountFunArgs(arguments)
let pos = 0
let ac = 0 " arg count
let arguments = a:arguments
" Change list / tuples into just one A(rgument)
let erlangTuple = '{\([A-Za-z_,|=\-\[\]]\|\s\)*}'
let erlangList = '\[\([A-Za-z_,|=\-{}]\|\s\)*\]'
function ErlangFoldText()
let line = getline(v:foldstart)
let foldlen = v:foldend - v:foldstart + 1
let lines = ' ' . foldlen . ' lines: ' . substitute(line, "[ \t]*", '', '')
if foldlen < 10
let lines = ' ' . lines
endif
let retval = '+' . v:folddashes . lines
" FIXME: Use searchpair?
while arguments =~ erlangTuple
let arguments = substitute(arguments, erlangTuple, "A", "g")
endwhile
" FIXME: Use searchpair?
while arguments =~ erlangList
let arguments = substitute(arguments, erlangList, "A", "g")
endwhile
let len = strlen(arguments)
while pos < len && pos > -1
let ac += 1
let pos = matchend(arguments, ',\s*', pos)
endwhile
return ac
endfunction
return retval
endfunction
" Main fold function
function GetErlangFold(lnum)
let lnum = a:lnum
let line = getline(lnum)
if line =~ s:ErlangFunEnd
return '<1'
endif
if line =~ s:ErlangFunBegin && foldlevel(lnum - 1) == 1
if exists("g:erlangFoldSplitFunction") && g:erlangFoldSplitFunction
return '>1'
else
return '1'
endif
endif
if line =~ s:ErlangFunBegin
return '>1'
endif
return '='
endfunction
" Erlang fold description (foldtext function)
function ErlangFoldText()
let foldlen = v:foldend - v:foldstart
if 1 < foldlen
let lines = "lines"
else
let lines = "line"
endif
let line = getline(v:foldstart)
let name = s:GetFunName(line)
let arguments = s:GetFunArgs(strpart(line, strlen(name)), v:foldstart)
let argcount = s:CountFunArgs(arguments)
let retval = "+" . v:folddashes . " " . name . "/" . argcount
let retval .= " (" . foldlen . " " . lines . ")"
return retval
endfunction
endif
call s:SetErlangOptions()

View File

@@ -0,0 +1,295 @@
" Erlang refactor file
" Language: Erlang
" Maintainer: Pawel 'kTT' Salata <rockplayer.pl@gmail.com>
" URL: http://ktototaki.info
if exists("b:did_ftplugin_erlang")
finish
endif
" Don't load any other
let b:did_ftplugin_erlang=1
if !exists('g:erlangRefactoring') || g:erlangRefactoring == 0
finish
endif
if !exists('g:erlangWranglerPath')
let g:erlangWranglerPath = '/usr/share/wrangler/'
endif
if glob(g:erlangWranglerPath) == ""
call confirm("Wrong path to wrangler dir")
finish
endif
autocmd VimLeavePre * call StopWranglerServer()
let s:erlangServerName = "wrangler_vim"
" Starting background erlang session with wrangler on
function! StartWranglerServer()
let wranglerEbinDir = g:erlangWranglerPath . "/ebin"
let command = "erl_call -s -sname " . s:erlangServerName . " -x 'erl -pa " . wranglerEbinDir . "'"
call system(command)
call s:send_rpc('application', 'start', '[wrangler_app]')
endfunction
" Stopping erlang session
function! StopWranglerServer()
echo s:send_rpc('erlang', 'halt', '')
endfunction
" Sending rpc call to erlang session
function! s:send_rpc(module, fun, args)
let command = "erl_call -sname " . s:erlangServerName . " -a '" . a:module . " " . a:fun . " " . a:args . "'"
let result = system(command)
if match(result, 'erl_call: failed to connect to node .*') != -1
call StartWranglerServer()
return system(command)
endif
return result
endfunction
function! ErlangUndo()
echo s:send_rpc("wrangler_undo_server", "undo", "[]")
:e!
endfunction
function! s:trim(text)
return substitute(a:text, "^\\s\\+\\|\\s\\+$", "", "g")
endfunction
function! s:get_msg(result, tuple_start)
let msg_begin = '{' . a:tuple_start . ','
let matching_start = match(a:result, msg_begin)
if matching_start != -1
return s:trim(matchstr(a:result, '[^}]*', matching_start + strlen(msg_begin)))
endif
return ""
endfunction
" Check if there is an error in result
function! s:check_for_error(result)
let msg = s:get_msg(a:result, 'ok')
if msg != ""
return [0, msg]
endif
let msg = s:get_msg(a:result, 'warning')
if msg != ""
return [1, msg]
endif
let msg = s:get_msg(a:result, 'error')
if msg != ""
return [2, msg]
endif
return [-1, ""]
endfunction
" Sending apply changes to file
function! s:send_confirm()
let choice = confirm("What do you want?", "&Preview\n&Confirm\nCa&ncel", 0)
if choice == 1
echo "TODO: Display preview :)"
elseif choice == 2
let module = 'wrangler_preview_server'
let fun = 'commit'
let args = '[]'
return s:send_rpc(module, fun, args)
else
let module = 'wrangler_preview_server'
let fun = 'abort'
let args = '[]'
return s:send_rpc(module, fun, args)
echo "Canceled"
endif
endfunction
" Manually send confirm, for testing purpose only
function! SendConfirm()
echo s:send_confirm()
endfunction
" Format and send function extracton call
function! s:call_extract(start_line, start_col, end_line, end_col, name)
let file = expand("%:p")
let module = 'wrangler'
let fun = 'fun_extraction'
let args = '["' . file . '", {' . a:start_line . ', ' . a:start_col . '}, {' . a:end_line . ', ' . a:end_col . '}, "' . a:name . '", ' . &sw . ']'
let result = s:send_rpc(module, fun, args)
let [error_code, msg] = s:check_for_error(result)
if error_code != 0
call confirm(msg)
return 0
endif
echo "This files will be changed: " . matchstr(msg, "[^]]*", 1)
echo s:send_confirm()
return 1
endfunction
function! ErlangExtractFunction(mode) range
silent w!
let name = inputdialog("New function name: ")
if name != ""
if a:mode == "v"
let start_pos = getpos("'<")
let start_line = start_pos[1]
let start_col = start_pos[2]
let end_pos = getpos("'>")
let end_line = end_pos[1]
let end_col = end_pos[2]
elseif a:mode == "n"
let pos = getpos(".")
let start_line = pos[1]
let start_col = pos[2]
let end_line = pos[1]
let end_col = pos[2]
else
echo "Mode not supported."
return
endif
if s:call_extract(start_line, start_col, end_line, end_col, name)
let temp = &autoread
set autoread
:e
if temp == 0
set noautoread
endif
endif
else
echo "Empty function name. Ignoring."
endif
endfunction
nmap <A-r>e :call ErlangExtractFunction("n")<ENTER>
vmap <A-r>e :call ErlangExtractFunction("v")<ENTER>
function! s:call_rename(mode, line, col, name, search_path)
let file = expand("%:p")
let module = 'wrangler'
let fun = 'rename_' . a:mode
let args = '["' . file .'", '
if a:mode != "mod"
let args = args . a:line . ', ' . a:col . ', '
endif
let args = args . '"' . a:name . '", ["' . a:search_path . '"], ' . &sw . ']'
let result = s:send_rpc(module, fun, args)
let [error_code, msg] = s:check_for_error(result)
if error_code != 0
call confirm(msg)
return 0
endif
echo "This files will be changed: " . matchstr(msg, "[^]]*", 1)
echo s:send_confirm()
return 1
endfunction
function! ErlangRename(mode)
silent w!
if a:mode == "mod"
let name = inputdialog('Rename module to: ')
else
let name = inputdialog('Rename "' . expand("<cword>") . '" to: ')
endif
if name != ""
let search_path = expand("%:p:h")
"let search_path = inputdialog('Search path: ', expand("%:p:h"))
let pos = getpos(".")
let line = pos[1]
let col = pos[2]
let current_filename = expand("%")
let current_filepath = expand("%:p")
let new_filename = name . '.erl'
if s:call_rename(a:mode, line, col, name, search_path)
if a:mode == "mod"
execute ':bd ' . current_filename
execute ':e ' . new_filename
silent execute '!mv ' . current_filepath . ' ' . current_filepath . '.bak'
redraw!
else
let temp = &autoread
set autoread
:e
if temp == 0
set noautoread
endif
endif
endif
else
echo "Empty name. Ignoring."
endif
endfunction
function! ErlangRenameFunction()
call ErlangRename("fun")
endfunction
map <A-r>f :call ErlangRenameFunction()<ENTER>
function! ErlangRenameVariable()
call ErlangRename("var")
endfunction
map <A-r>v :call ErlangRenameVariable()<ENTER>
function! ErlangRenameModule()
call ErlangRename("mod")
endfunction
map <A-r>m :call ErlangRenameModule()<ENTER>
function! ErlangRenameProcess()
call ErlangRename("process")
endfunction
map <A-r>p :call ErlangRenameProcess()<ENTER>
function! s:call_tuple_fun_args(start_line, start_col, end_line, end_col, search_path)
let file = expand("%:p")
let module = 'wrangler'
let fun = 'tuple_funpar'
let args = '["' . file . '", {' . a:start_line . ', ' . a:start_col . '}, {' . a:end_line . ', ' . a:end_col . '}, ["' . a:search_path . '"], ' . &sw . ']'
let result = s:send_rpc(module, fun, args)
if s:check_for_error(result)
return 0
endif
call s:send_confirm()
return 1
endfunction
function! ErlangTupleFunArgs(mode)
silent w!
let search_path = expand("%:p:h")
"let search_path = inputdialog('Search path: ', expand("%:p:h"))
if a:mode == "v"
let start_pos = getpos("'<")
let start_line = start_pos[1]
let start_col = start_pos[2]
let end_pos = getpos("'>")
let end_line = end_pos[1]
let end_col = end_pos[2]
if s:call_tuple_fun_args(start_line, start_col, end_line, end_col, search_path)
let temp = &autoread
set autoread
:e
if temp == 0
set noautoread
endif
endif
elseif a:mode == "n"
let pos = getpos(".")
let line = pos[1]
let col = pos[2]
if s:call_tuple_fun_args(line, col, line, col, search_path)
let temp = &autoread
set autoread
:e
if temp == 0
set noautoread
endif
endif
else
echo "Mode not supported."
endif
endfunction
nmap <A-r>t :call ErlangTupleFunArgs("n")<ENTER>
vmap <A-r>t :call ErlangTupleFunArgs("v")<ENTER>
" vim: set foldmethod=marker:

17
ftplugin/go.vim Normal file
View File

@@ -0,0 +1,17 @@
" Copyright 2013 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" go.vim: Vim filetype plugin for Go.
if exists("b:did_ftplugin")
finish
endif
let b:did_ftplugin = 1
setlocal comments=s1:/*,mb:*,ex:*/,://
setlocal commentstring=//\ %s
let b:undo_ftplugin = "setl com< cms<"
" vim:ts=4:sw=4:et

View File

@@ -12,15 +12,35 @@
" It tries to preserve cursor position and avoids
" replacing the buffer with stderr output.
"
" Options:
"
" g:go_fmt_commands [default=1]
"
" Flag to indicate whether to enable the commands listed above.
"
" g:gofmt_command [default="gofmt"]
"
" Flag naming the gofmt executable to use.
"
if exists("b:did_ftplugin_go_fmt")
finish
endif
command! -buffer Fmt call s:GoFormat()
if !exists("g:go_fmt_commands")
let g:go_fmt_commands = 1
endif
if !exists("g:gofmt_command")
let g:gofmt_command = "gofmt"
endif
if g:go_fmt_commands
command! -buffer Fmt call s:GoFormat()
endif
function! s:GoFormat()
let view = winsaveview()
silent %!gofmt
silent execute "%!" . g:gofmt_command
if v:shell_error
let errors = []
for line in getline(1, line('$'))
@@ -37,7 +57,7 @@ function! s:GoFormat()
endif
undo
if !empty(errors)
call setloclist(0, errors, 'r')
call setqflist(errors, 'r')
endif
echohl Error | echomsg "Gofmt returned error" | echohl None
endif

View File

@@ -24,23 +24,40 @@
" imported, an error will be displayed and the buffer will be
" untouched.
"
" In addition to these commands, there are also two shortcuts mapped:
" If you would like to add shortcuts, you can do so by doing the following:
"
" \f - Runs :Import fmt
" \F - Runs :Drop fmt
" Import fmt
" au Filetype go nnoremap <buffer> <LocalLeader>f :Import fmt<CR>
"
" The backslash is the default maplocalleader, so it is possible that
" Drop fmt
" au Filetype go nnoremap <buffer> <LocalLeader>F :Drop fmt<CR>
"
" Import the word under your cursor
" au Filetype go nnoremap <buffer> <LocalLeader>k
" \ :exe 'Import ' . expand('<cword>')<CR>
"
" The backslash '\' is the default maplocalleader, so it is possible that
" your vim is set to use a different character (:help maplocalleader).
"
" Options:
"
" g:go_import_commands [default=1]
"
" Flag to indicate whether to enable the commands listed above.
"
if exists("b:did_ftplugin_go_import")
finish
endif
command! -buffer -nargs=? -complete=customlist,go#complete#Package Drop call s:SwitchImport(0, '', <f-args>)
command! -buffer -nargs=1 -complete=customlist,go#complete#Package Import call s:SwitchImport(1, '', <f-args>)
command! -buffer -nargs=* -complete=customlist,go#complete#Package ImportAs call s:SwitchImport(1, <f-args>)
map <buffer> <LocalLeader>f :Import fmt<CR>
map <buffer> <LocalLeader>F :Drop fmt<CR>
if !exists("g:go_import_commands")
let g:go_import_commands = 1
endif
if g:go_import_commands
command! -buffer -nargs=? -complete=customlist,go#complete#Package Drop call s:SwitchImport(0, '', <f-args>)
command! -buffer -nargs=1 -complete=customlist,go#complete#Package Import call s:SwitchImport(1, '', <f-args>)
command! -buffer -nargs=* -complete=customlist,go#complete#Package ImportAs call s:SwitchImport(1, <f-args>)
endif
function! s:SwitchImport(enabled, localname, path)
let view = winsaveview()

View File

@@ -1,22 +0,0 @@
" Taken from https://github.com/juvenn/mustache.vim/blob/master/ftplugin/mustache.vim
let s:cpo_save = &cpo
set cpo&vim
" Matchit support for Handlebars
" extending HTML matchit groups
if exists("loaded_matchit") && exists("b:match_words")
let b:match_words = b:match_words
\ . ',{:},[:],(:),'
\ . '\%({{\)\@<=#\s*\%(if\|unless\)\s*.\{-}}}'
\ . ':'
\ . '\%({{\)\@<=\s*else\s*}}'
\ . ':'
\ . '\%({{\)\@<=/\s*\%(if\|unless\)\s*}},'
\ . '\%({{\)\@<=[#^]\s*\([-0-9a-zA-Z_?!/.]\+\).\{-}}}'
\ . ':'
\ . '\%({{\)\@<=/\s*\1\s*}}'
endif
let &cpo = s:cpo_save
unlet s:cpo_save

55
ftplugin/jade.vim Normal file
View File

@@ -0,0 +1,55 @@
" Vim filetype plugin
" Language: Jade
" Maintainer: Joshua Borton
" Credits: Tim Pope
" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
finish
endif
let s:save_cpo = &cpo
set cpo-=C
" Define some defaults in case the included ftplugins don't set them.
let s:undo_ftplugin = ""
let s:browsefilter = "All Files (*.*)\t*.*\n"
let s:match_words = ""
runtime! ftplugin/html.vim ftplugin/html_*.vim ftplugin/html/*.vim
unlet! b:did_ftplugin
" Override our defaults if these were set by an included ftplugin.
if exists("b:undo_ftplugin")
let s:undo_ftplugin = b:undo_ftplugin
unlet b:undo_ftplugin
endif
if exists("b:browsefilter")
let s:browsefilter = b:browsefilter
unlet b:browsefilter
endif
if exists("b:match_words")
let s:match_words = b:match_words
unlet b:match_words
endif
" Change the browse dialog on Win32 to show mainly Haml-related files
if has("gui_win32")
let b:browsefilter="Jade Files (*.jade)\t*.jade\n" . s:browsefilter
endif
" Load the combined list of match_words for matchit.vim
if exists("loaded_matchit")
let b:match_words = s:match_words
endif
setlocal comments=://-,:// commentstring=//\ %s
setlocal suffixesadd+=.jade
let b:undo_ftplugin = "setl cms< com< "
\ " | unlet! b:browsefilter b:match_words | " . s:undo_ftplugin
let &cpo = s:save_cpo
" vim:set sw=2:

View File

@@ -0,0 +1,360 @@
" LaTeX Box common functions
" Error Format {{{
" Note: The error formats assume we're using the -file-line-error with
" [pdf]latex.
" Note: See |errorformat-LaTeX| for more info.
" Check for options
if !exists("g:LatexBox_show_warnings")
let g:LatexBox_show_warnings=1
endif
if !exists("g:LatexBox_ignore_warnings")
let g:LatexBox_ignore_warnings =
\['Underfull',
\ 'Overfull',
\ 'specifier changed to']
endif
" Standard error message formats
" Note: We consider statements that starts with "!" as errors
setlocal efm=%E!\ LaTeX\ %trror:\ %m
setlocal efm+=%E%f:%l:\ %m
setlocal efm+=%E!\ %m
" More info for undefined control sequences
setlocal efm+=%Z<argument>\ %m
" Show or ignore warnings
if g:LatexBox_show_warnings
for w in g:LatexBox_ignore_warnings
let warning = escape(substitute(w, '[\,]', '%\\\\&', 'g'), ' ')
exe 'setlocal efm+=%-G%.%#'. warning .'%.%#'
endfor
setlocal efm+=%+WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%#
setlocal efm+=%+W%.%#\ at\ lines\ %l--%*\\d
setlocal efm+=%+WLaTeX\ %.%#Warning:\ %m
setlocal efm+=%+W%.%#Warning:\ %m
else
setlocal efm+=%-WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%#
setlocal efm+=%-W%.%#\ at\ lines\ %l--%*\\d
setlocal efm+=%-WLaTeX\ %.%#Warning:\ %m
setlocal efm+=%-W%.%#Warning:\ %m
endif
" Push file to file stack
setlocal efm+=%+P**%f
" Ignore unmatched lines
setlocal efm+=%-G%.%#
" }}}
" Vim Windows {{{
" Width of vertical splits
if !exists('g:LatexBox_split_width')
let g:LatexBox_split_width = 30
endif
" Where vertical splits appear
if !exists('g:LatexBox_split_side')
let g:LatexBox_split_side = "leftabove"
endif
" Resize when split?
if !exists('g:LatexBox_split_resize')
let g:LatexBox_split_resize = 0
endif
" Toggle help info
if !exists('g:LatexBox_toc_hidehelp')
let g:LatexBox_toc_hidehelp = 0
endif
" }}}
" Filename utilities {{{
function! LatexBox_GetMainTexFile()
" 1. check for the b:main_tex_file variable
if exists('b:main_tex_file') && filereadable(b:main_tex_file)
return b:main_tex_file
endif
" 2. scan the first few lines of the file for root = filename
for linenum in range(1,5)
let linecontents = getline(linenum)
if linecontents =~ 'root\s*='
" Remove everything but the filename
let b:main_tex_file = substitute(linecontents,
\ '.*root\s*=\s*', "", "")
let b:main_tex_file = substitute(b:main_tex_file, '\s*$', "", "")
" Prepend current directory if this isn't an absolute path
if b:main_tex_file !~ '^/'
let b:main_tex_file = expand('%:p:h') . '/' . b:main_tex_file
endif
let b:main_tex_file = fnamemodify(b:main_tex_file, ":p")
if b:main_tex_file !~ '\.tex$'
let b:main_tex_file .= '.tex'
endif
return b:main_tex_file
endif
endfor
" 3. scan current file for "\begin{document}"
if &filetype == 'tex' && search('\C\\begin\_\s*{document}', 'nw') != 0
return expand('%:p')
endif
" 4. use 'main.tex' if it exists in the same directory (and is readable)
let s:main_dot_tex_file=expand('%:p:h') . '/main.tex'
if filereadable(s:main_dot_tex_file)
let b:main_tex_file=s:main_dot_tex_file
return b:main_tex_file
endif
" 5. borrow the Vim-Latex-Suite method of finding it
if Tex_GetMainFileName() != expand('%:p')
let b:main_tex_file = Tex_GetMainFileName()
return b:main_tex_file
endif
" 6. prompt for file with completion
let b:main_tex_file = s:PromptForMainFile()
return b:main_tex_file
endfunction
function! s:PromptForMainFile()
let saved_dir = getcwd()
execute 'cd ' . fnameescape(expand('%:p:h'))
let l:file = ''
while !filereadable(l:file)
let l:file = input('main LaTeX file: ', '', 'file')
if l:file !~ '\.tex$'
let l:file .= '.tex'
endif
endwhile
let l:file = fnamemodify(l:file, ':p')
execute 'cd ' . fnameescape(saved_dir)
return l:file
endfunction
" Return the directory of the main tex file
function! LatexBox_GetTexRoot()
return fnamemodify(LatexBox_GetMainTexFile(), ':h')
endfunction
function! LatexBox_GetTexBasename(with_dir)
if a:with_dir
return fnamemodify(LatexBox_GetMainTexFile(), ':r')
else
return fnamemodify(LatexBox_GetMainTexFile(), ':t:r')
endif
endfunction
function! LatexBox_GetAuxFile()
" 1. check for b:build_dir variable
if exists('b:build_dir') && isdirectory(b:build_dir)
return b:build_dir . '/' . LatexBox_GetTexBasename(0) . '.aux'
endif
" 2. check for g:LatexBox_build_dir variable
if exists('g:LatexBox_build_dir') && isdirectory(g:LatexBox_build_dir)
return g:LatexBox_build_dir . '/' . LatexBox_GetTexBasename(0) . '.aux'
endif
" 3. use the base name of main tex file
return LatexBox_GetTexBasename(1) . '.aux'
endfunction
function! LatexBox_GetLogFile()
" 1. check for b:build_dir variable
if exists('b:build_dir') && isdirectory(b:build_dir)
return b:build_dir . '/' . LatexBox_GetTexBasename(0) . '.log'
endif
" 2. check for g:LatexBox_build_dir variable
if exists('g:LatexBox_build_dir') && isdirectory(g:LatexBox_build_dir)
return g:LatexBox_build_dir . '/' . LatexBox_GetTexBasename(0) . '.log'
endif
" 3. use the base name of main tex file
return LatexBox_GetTexBasename(1) . '.log'
endfunction
function! LatexBox_GetOutputFile()
" 1. check for b:build_dir variable
if exists('b:build_dir') && isdirectory(b:build_dir)
return b:build_dir . '/' . LatexBox_GetTexBasename(0)
\ . '.' . g:LatexBox_output_type
endif
" 2. check for g:LatexBox_build_dir variable
if exists('g:LatexBox_build_dir') && isdirectory(g:LatexBox_build_dir)
return g:LatexBox_build_dir . '/' . LatexBox_GetTexBasename(0)
\ . '.' . g:LatexBox_output_type
endif
" 3. use the base name of main tex file
return LatexBox_GetTexBasename(1) . '.' . g:LatexBox_output_type
endfunction
" }}}
" View Output {{{
" Default pdf viewer
if !exists('g:LatexBox_viewer')
if has('win32')
" On windows, 'running' a file will open it with the default program
let g:LatexBox_viewer = ''
else
let g:LatexBox_viewer = 'xdg-open'
endif
endif
function! LatexBox_View()
let outfile = LatexBox_GetOutputFile()
if !filereadable(outfile)
echomsg fnamemodify(outfile, ':.') . ' is not readable'
return
endif
let cmd = g:LatexBox_viewer . ' ' . shellescape(outfile)
if has('win32')
let cmd = '!start /b' . cmd . ' >nul'
else
let cmd = '!' . cmd . ' &>/dev/null &'
endif
silent execute cmd
if !has("gui_running")
redraw!
endif
endfunction
command! LatexView call LatexBox_View()
" }}}
" In Comment {{{
" LatexBox_InComment([line], [col])
" return true if inside comment
function! LatexBox_InComment(...)
let line = a:0 >= 1 ? a:1 : line('.')
let col = a:0 >= 2 ? a:2 : col('.')
return synIDattr(synID(line, col, 0), "name") =~# '^texComment'
endfunction
" }}}
" Get Current Environment {{{
" LatexBox_GetCurrentEnvironment([with_pos])
" Returns:
" - environment
" if with_pos is not given
" - [envirnoment, lnum_begin, cnum_begin, lnum_end, cnum_end]
" if with_pos is nonzero
function! LatexBox_GetCurrentEnvironment(...)
if a:0 > 0
let with_pos = a:1
else
let with_pos = 0
endif
let begin_pat = '\C\\begin\_\s*{[^}]*}\|\\\@<!\\\[\|\\\@<!\\('
let end_pat = '\C\\end\_\s*{[^}]*}\|\\\@<!\\\]\|\\\@<!\\)'
let saved_pos = getpos('.')
" move to the left until on a backslash
let [bufnum, lnum, cnum, off] = getpos('.')
let line = getline(lnum)
while cnum > 1 && line[cnum - 1] != '\'
let cnum -= 1
endwhile
call cursor(lnum, cnum)
" match begin/end pairs but skip comments
let flags = 'bnW'
if strpart(getline('.'), col('.') - 1) =~ '^\%(' . begin_pat . '\)'
let flags .= 'c'
endif
let [lnum1, cnum1] = searchpairpos(begin_pat, '', end_pat, flags,
\ 'LatexBox_InComment()')
let env = ''
if lnum1
let line = strpart(getline(lnum1), cnum1 - 1)
if empty(env)
let env = matchstr(line, '^\C\\begin\_\s*{\zs[^}]*\ze}')
endif
if empty(env)
let env = matchstr(line, '^\\\[')
endif
if empty(env)
let env = matchstr(line, '^\\(')
endif
endif
if with_pos == 1
let flags = 'nW'
if !(lnum1 == lnum && cnum1 == cnum)
let flags .= 'c'
endif
let [lnum2, cnum2] = searchpairpos(begin_pat, '', end_pat, flags,
\ 'LatexBox_InComment()')
call setpos('.', saved_pos)
return [env, lnum1, cnum1, lnum2, cnum2]
else
call setpos('.', saved_pos)
return env
endif
endfunction
" }}}
" Tex To Tree {{{
" stores nested braces in a tree structure
function! LatexBox_TexToTree(str)
let tree = []
let i1 = 0
let i2 = -1
let depth = 0
while i2 < len(a:str)
let i2 = match(a:str, '[{}]', i2 + 1)
if i2 < 0
let i2 = len(a:str)
endif
if i2 >= len(a:str) || a:str[i2] == '{'
if depth == 0
let item = substitute(strpart(a:str, i1, i2 - i1),
\ '^\s*\|\s*$', '', 'g')
if !empty(item)
call add(tree, item)
endif
let i1 = i2 + 1
endif
let depth += 1
else
let depth -= 1
if depth == 0
call add(tree, LatexBox_TexToTree(strpart(a:str, i1, i2 - i1)))
let i1 = i2 + 1
endif
endif
endwhile
return tree
endfunction
" }}}
" Tree To Tex {{{
function! LatexBox_TreeToTex(tree)
if type(a:tree) == type('')
return a:tree
else
return '{' . join(map(a:tree, 'LatexBox_TreeToTex(v:val)'), '') . '}'
endif
endfunction
" }}}
" vim:fdm=marker:ff=unix:noet:ts=4:sw=4

View File

@@ -0,0 +1,861 @@
" LaTeX Box completion
setlocal omnifunc=LatexBox_Complete
" <SID> Wrap {{{
function! s:GetSID()
return matchstr(expand('<sfile>'), '\zs<SNR>\d\+_\ze.*$')
endfunction
let s:SID = s:GetSID()
function! s:SIDWrap(func)
return s:SID . a:func
endfunction
" }}}
" Completion {{{
if !exists('g:LatexBox_completion_close_braces')
let g:LatexBox_completion_close_braces = 1
endif
if !exists('g:LatexBox_bibtex_wild_spaces')
let g:LatexBox_bibtex_wild_spaces = 1
endif
if !exists('g:LatexBox_cite_pattern')
let g:LatexBox_cite_pattern = '\C\\\a*cite\a*\*\?\(\[[^\]]*\]\)*\_\s*{'
endif
if !exists('g:LatexBox_ref_pattern')
let g:LatexBox_ref_pattern = '\C\\v\?\(eq\|page\|[cC]\|labelc\)\?ref\*\?\_\s*{'
endif
if !exists('g:LatexBox_completion_environments')
let g:LatexBox_completion_environments = [
\ {'word': 'itemize', 'menu': 'bullet list' },
\ {'word': 'enumerate', 'menu': 'numbered list' },
\ {'word': 'description', 'menu': 'description' },
\ {'word': 'center', 'menu': 'centered text' },
\ {'word': 'figure', 'menu': 'floating figure' },
\ {'word': 'table', 'menu': 'floating table' },
\ {'word': 'equation', 'menu': 'equation (numbered)' },
\ {'word': 'align', 'menu': 'aligned equations (numbered)' },
\ {'word': 'align*', 'menu': 'aligned equations' },
\ {'word': 'document' },
\ {'word': 'abstract' },
\ ]
endif
if !exists('g:LatexBox_completion_commands')
let g:LatexBox_completion_commands = [
\ {'word': '\begin{' },
\ {'word': '\end{' },
\ {'word': '\item' },
\ {'word': '\label{' },
\ {'word': '\ref{' },
\ {'word': '\eqref{eq:' },
\ {'word': '\cite{' },
\ {'word': '\chapter{' },
\ {'word': '\section{' },
\ {'word': '\subsection{' },
\ {'word': '\subsubsection{' },
\ {'word': '\paragraph{' },
\ {'word': '\nonumber' },
\ {'word': '\bibliography' },
\ {'word': '\bibliographystyle' },
\ ]
endif
if !exists('g:LatexBox_complete_inlineMath')
let g:LatexBox_complete_inlineMath = 0
endif
if !exists('g:LatexBox_eq_env_patterns')
let g:LatexBox_eq_env_patterns = 'equation\|gather\|multiline\|align\|flalign\|alignat\|eqnarray'
endif
" }}}
"LatexBox_kpsewhich {{{
function! LatexBox_kpsewhich(file)
let old_dir = getcwd()
execute 'lcd ' . fnameescape(LatexBox_GetTexRoot())
let out = system('kpsewhich "' . a:file . '"')
" If kpsewhich has found something, it returns a non-empty string with a
" newline at the end; otherwise the string is empty
if len(out)
" Remove the trailing newline
let out = fnamemodify(out[:-2], ':p')
endif
execute 'lcd ' . fnameescape(old_dir)
return out
endfunction
"}}}
" Omni Completion {{{
let s:completion_type = ''
function! LatexBox_Complete(findstart, base)
if a:findstart
" return the starting position of the word
let line = getline('.')
let pos = col('.') - 1
while pos > 0 && line[pos - 1] !~ '\\\|{'
let pos -= 1
endwhile
let line_start = line[:pos-1]
if line_start =~ '\C\\begin\_\s*{$'
let s:completion_type = 'begin'
elseif line_start =~ '\C\\end\_\s*{$'
let s:completion_type = 'end'
elseif line_start =~ g:LatexBox_ref_pattern . '$'
let s:completion_type = 'ref'
elseif line_start =~ g:LatexBox_cite_pattern . '$'
let s:completion_type = 'bib'
" check for multiple citations
let pos = col('.') - 1
while pos > 0 && line[pos - 1] !~ '{\|,'
let pos -= 1
endwhile
elseif s:LatexBox_complete_inlineMath_or_not()
let s:completion_type = 'inlineMath'
let pos = s:eq_pos
else
let s:completion_type = 'command'
if line[pos - 1] == '\'
let pos -= 1
endif
endif
return pos
else
" return suggestions in an array
let suggestions = []
if s:completion_type == 'begin'
" suggest known environments
for entry in g:LatexBox_completion_environments
if entry.word =~ '^' . escape(a:base, '\')
if g:LatexBox_completion_close_braces && !s:NextCharsMatch('^}')
" add trailing '}'
let entry = copy(entry)
let entry.abbr = entry.word
let entry.word = entry.word . '}'
endif
call add(suggestions, entry)
endif
endfor
elseif s:completion_type == 'end'
" suggest known environments
let env = LatexBox_GetCurrentEnvironment()
if env != ''
if g:LatexBox_completion_close_braces && !s:NextCharsMatch('^\s*[,}]')
call add(suggestions, {'word': env . '}', 'abbr': env})
else
call add(suggestions, env)
endif
endif
elseif s:completion_type == 'command'
" suggest known commands
for entry in g:LatexBox_completion_commands
if entry.word =~ '^' . escape(a:base, '\')
" do not display trailing '{'
if entry.word =~ '{'
let entry.abbr = entry.word[0:-2]
endif
call add(suggestions, entry)
endif
endfor
elseif s:completion_type == 'ref'
let suggestions = s:CompleteLabels(a:base)
elseif s:completion_type == 'bib'
" suggest BibTeX entries
let suggestions = LatexBox_BibComplete(a:base)
elseif s:completion_type == 'inlineMath'
let suggestions = s:LatexBox_inlineMath_completion(a:base)
endif
if !has('gui_running')
redraw!
endif
return suggestions
endif
endfunction
" }}}
" BibTeX search {{{
" find the \bibliography{...} commands
" the optional argument is the file name to be searched
function! s:FindBibData(...)
if a:0 == 0
let file = LatexBox_GetMainTexFile()
else
let file = a:1
endif
if !filereadable(file)
return []
endif
let lines = readfile(file)
let bibdata_list = []
"
" Search for added bibliographies
"
let bibliography_cmds = [
\ '\\bibliography',
\ '\\addbibresource',
\ '\\addglobalbib',
\ '\\addsectionbib',
\ ]
for cmd in bibliography_cmds
let filtered = filter(copy(lines),
\ 'v:val =~ ''\C' . cmd . '\s*{[^}]\+}''')
let files = map(filtered,
\ 'matchstr(v:val, ''\C' . cmd . '\s*{\zs[^}]\+\ze}'')')
for file in files
let bibdata_list += map(split(file, ','),
\ 'fnamemodify(v:val, '':r'')')
endfor
endfor
"
" Also search included files
"
for input in filter(lines,
\ 'v:val =~ ''\C\\\%(input\|include\)\s*{[^}]\+}''')
let bibdata_list += s:FindBibData(LatexBox_kpsewhich(
\ matchstr(input,
\ '\C\\\%(input\|include\)\s*{\zs[^}]\+\ze}')))
endfor
return bibdata_list
endfunction
let s:bstfile = expand('<sfile>:p:h') . '/vimcomplete'
function! LatexBox_BibSearch(regexp)
let res = []
" Find data from bib files
let bibdata = join(s:FindBibData(), ',')
if bibdata != ''
" write temporary aux file
let tmpbase = LatexBox_GetTexRoot() . '/_LatexBox_BibComplete'
let auxfile = tmpbase . '.aux'
let bblfile = tmpbase . '.bbl'
let blgfile = tmpbase . '.blg'
call writefile(['\citation{*}', '\bibstyle{' . s:bstfile . '}',
\ '\bibdata{' . bibdata . '}'], auxfile)
if has('win32')
let l:old_shellslash = &l:shellslash
setlocal noshellslash
silent execute '! cd ' shellescape(LatexBox_GetTexRoot()) .
\ ' & bibtex -terse '
\ . fnamemodify(auxfile, ':t') . ' >nul'
let &l:shellslash = l:old_shellslash
else
silent execute '! cd ' shellescape(LatexBox_GetTexRoot()) .
\ ' ; bibtex -terse '
\ . fnamemodify(auxfile, ':t') . ' >/dev/null'
endif
let lines = split(substitute(join(readfile(bblfile), "\n"),
\ '\n\n\@!\(\s\=\)\s*\|{\|}', '\1', 'g'), "\n")
for line in filter(lines, 'v:val =~ a:regexp')
let matches = matchlist(line,
\ '^\(.*\)||\(.*\)||\(.*\)||\(.*\)||\(.*\)')
if !empty(matches) && !empty(matches[1])
let s:type_length = max([s:type_length,
\ len(matches[2]) + 3])
call add(res, {
\ 'key': matches[1],
\ 'type': matches[2],
\ 'author': matches[3],
\ 'year': matches[4],
\ 'title': matches[5],
\ })
endif
endfor
call delete(auxfile)
call delete(bblfile)
call delete(blgfile)
endif
" Find data from 'thebibliography' environments
let lines = readfile(LatexBox_GetMainTexFile())
if match(lines, '\C\\begin{thebibliography}') >= 0
for line in filter(filter(lines, 'v:val =~ ''\C\\bibitem'''),
\ 'v:val =~ a:regexp')
let match = matchlist(line, '\\bibitem{\([^}]*\)')[1]
call add(res, {
\ 'key': match,
\ 'type': '',
\ 'author': '',
\ 'year': '',
\ 'title': match,
\ })
endfor
endif
return res
endfunction
" }}}
" BibTeX completion {{{
let s:type_length=0
function! LatexBox_BibComplete(regexp)
" treat spaces as '.*' if needed
if g:LatexBox_bibtex_wild_spaces
"let regexp = substitute(a:regexp, '\s\+', '.*', 'g')
let regexp = '.*' . substitute(a:regexp, '\s\+', '\\\&.*', 'g')
else
let regexp = a:regexp
endif
let res = []
let s:type_length = 4
for m in LatexBox_BibSearch(regexp)
let type = m['type'] == '' ? '[-]' : '[' . m['type'] . '] '
let type = printf('%-' . s:type_length . 's', type)
let auth = m['author'] == '' ? '' : m['author'][:20] . ' '
let auth = substitute(auth, '\~', ' ', 'g')
let year = m['year'] == '' ? '' : '(' . m['year'] . ')'
let w = { 'word': m['key'],
\ 'abbr': type . auth . year,
\ 'menu': m['title'] }
" close braces if needed
if g:LatexBox_completion_close_braces && !s:NextCharsMatch('^\s*[,}]')
let w.word = w.word . '}'
endif
call add(res, w)
endfor
return res
endfunction
" }}}
" ExtractLabels {{{
" Generate list of \newlabel commands in current buffer.
"
" Searches the current buffer for commands of the form
" \newlabel{name}{{number}{page}.*
" and returns list of [ name, number, page ] tuples.
function! s:ExtractLabels()
call cursor(1,1)
let matches = []
let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' )
while [lblline, lblbegin] != [0,0]
let [nln, nameend] = searchpairpos( '{', '', '}', 'W' )
if nln != lblline
let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' )
continue
endif
let curname = strpart( getline( lblline ), lblbegin, nameend - lblbegin - 1 )
" Ignore cref entries (because they are duplicates)
if curname =~ "\@cref\|cref\@"
continue
endif
if 0 == search( '{\w*{', 'ce', lblline )
let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' )
continue
endif
let numberbegin = getpos('.')[2]
let [nln, numberend] = searchpairpos( '{', '', '}', 'W' )
if nln != lblline
let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' )
continue
endif
let curnumber = strpart( getline( lblline ), numberbegin, numberend - numberbegin - 1 )
if 0 == search( '\w*{', 'ce', lblline )
let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' )
continue
endif
let pagebegin = getpos('.')[2]
let [nln, pageend] = searchpairpos( '{', '', '}', 'W' )
if nln != lblline
let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' )
continue
endif
let curpage = strpart( getline( lblline ), pagebegin, pageend - pagebegin - 1 )
let matches += [ [ curname, curnumber, curpage ] ]
let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' )
endwhile
return matches
endfunction
"}}}
" ExtractInputs {{{
" Generate list of \@input commands in current buffer.
"
" Searches the current buffer for \@input{file} entries and
" returns list of all files.
function! s:ExtractInputs()
call cursor(1,1)
let matches = []
let [inline, inbegin] = searchpos( '\\@input{', 'ecW' )
while [inline, inbegin] != [0,0]
let [nln, inend] = searchpairpos( '{', '', '}', 'W' )
if nln != inline
let [inline, inbegin] = searchpos( '\\@input{', 'ecW' )
continue
endif
let matches += [ LatexBox_kpsewhich(strpart( getline( inline ), inbegin, inend - inbegin - 1 )) ]
let [inline, inbegin] = searchpos( '\\@input{', 'ecW' )
endwhile
" Remove empty strings for nonexistant .aux files
return filter(matches, 'v:val != ""')
endfunction
"}}}
" LabelCache {{{
" Cache of all labels.
"
" LabelCache is a dictionary mapping filenames to tuples
" [ time, labels, inputs ]
" where
" * time is modification time of the cache entry
" * labels is a list like returned by ExtractLabels
" * inputs is a list like returned by ExtractInputs
let s:LabelCache = {}
"}}}
" GetLabelCache {{{
" Extract labels from LabelCache and update it.
"
" Compares modification time of each entry in the label
" cache and updates it, if necessary. During traversal of
" the LabelCache, all current labels are collected and
" returned.
function! s:GetLabelCache(file)
if !filereadable(a:file)
return []
endif
if !has_key(s:LabelCache , a:file) || s:LabelCache[a:file][0] != getftime(a:file)
" Open file in temporary split window for label extraction.
silent execute '1sp +let\ labels=s:ExtractLabels()|let\ inputs=s:ExtractInputs()|quit! ' . fnameescape(a:file)
let s:LabelCache[a:file] = [ getftime(a:file), labels, inputs ]
endif
" We need to create a copy of s:LabelCache[fid][1], otherwise all inputs'
" labels would be added to the current file's label cache upon each
" completion call, leading to duplicates/triplicates/etc. and decreased
" performance.
" Also, because we don't anything with the list besides matching copies,
" we can get away with a shallow copy for now.
let labels = copy(s:LabelCache[a:file][1])
for input in s:LabelCache[a:file][2]
let labels += s:GetLabelCache(input)
endfor
return labels
endfunction
"}}}
" Complete Labels {{{
function! s:CompleteLabels(regex)
let labels = s:GetLabelCache(LatexBox_GetAuxFile())
let matches = filter( copy(labels), 'match(v:val[0], "' . a:regex . '") != -1' )
if empty(matches)
" also try to match label and number
let regex_split = split(a:regex)
if len(regex_split) > 1
let base = regex_split[0]
let number = escape(join(regex_split[1:], ' '), '.')
let matches = filter( copy(labels), 'match(v:val[0], "' . base . '") != -1 && match(v:val[1], "' . number . '") != -1' )
endif
endif
if empty(matches)
" also try to match number
let matches = filter( copy(labels), 'match(v:val[1], "' . a:regex . '") != -1' )
endif
let suggestions = []
for m in matches
let entry = {'word': m[0], 'menu': printf("%7s [p. %s]", '('.m[1].')', m[2])}
if g:LatexBox_completion_close_braces && !s:NextCharsMatch('^\s*[,}]')
" add trailing '}'
let entry = copy(entry)
let entry.abbr = entry.word
let entry.word = entry.word . '}'
endif
call add(suggestions, entry)
endfor
return suggestions
endfunction
" }}}
" Complete Inline Math Or Not {{{
" Return 1, when cursor is in a math env:
" 1, there is a single $ in the current line on the left of cursor
" 2, there is an open-eq-env on/above the current line
" (open-eq-env : \(, \[, and \begin{eq-env} )
" Return 0, when cursor is not in a math env
function! s:LatexBox_complete_inlineMath_or_not()
" switch of inline math completion feature
if g:LatexBox_complete_inlineMath == 0
return 0
endif
" env names that can't appear in an eq env
if !exists('s:LatexBox_doc_structure_patterns')
let s:LatexBox_doc_structure_patterns = '\%(' . '\\begin\s*{document}\|' .
\ '\\\%(chapter\|section\|subsection\|subsubsection\)\*\?\s*{' . '\)'
endif
if !exists('s:LatexBox_eq_env_open_patterns')
let s:LatexBox_eq_env_open_patterns = ['\\(','\\\[']
endif
if !exists('s:LatexBox_eq_env_close_patterns')
let s:LatexBox_eq_env_close_patterns = ['\\)','\\\]']
endif
let notcomment = '\%(\%(\\\@<!\%(\\\\\)*\)\@<=%.*\)\@<!'
let lnum_saved = line('.')
let cnum_saved = col('.') -1
let line = getline('.')
let line_start_2_cnum_saved = line[:cnum_saved]
" determine whether there is a single $ before cursor
let cursor_dollar_pair = 0
while matchend(line_start_2_cnum_saved, '\$[^$]\+\$', cursor_dollar_pair) >= 0
" find the end of dollar pair
let cursor_dollar_pair = matchend(line_start_2_cnum_saved, '\$[^$]\+\$', cursor_dollar_pair)
endwhile
" find single $ after cursor_dollar_pair
let cursor_single_dollar = matchend(line_start_2_cnum_saved, '\$', cursor_dollar_pair)
" if single $ is found
if cursor_single_dollar >= 0
" check whether $ is in \(...\), \[...\], or \begin{eq}...\end{eq}
" check current line,
" search for LatexBox_eq_env_close_patterns: \[ and \(
let lnum = line('.')
for i in range(0, (len(s:LatexBox_eq_env_open_patterns)-1))
call cursor(lnum_saved, cnum_saved)
let cnum_close = searchpos(''. s:LatexBox_eq_env_close_patterns[i].'', 'cbW', lnum_saved)[1]
let cnum_open = matchend(line_start_2_cnum_saved, s:LatexBox_eq_env_open_patterns[i], cnum_close)
if cnum_open >= 0
let s:eq_dollar_parenthesis_bracket_empty = ''
let s:eq_pos = cursor_single_dollar - 1
return 1
end
endfor
" check the lines above
" search for s:LatexBox_doc_structure_patterns, and end-of-math-env
let lnum -= 1
while lnum > 0
let line = getline(lnum)
if line =~ notcomment . '\(' . s:LatexBox_doc_structure_patterns .
\ '\|' . '\\end\s*{\(' . g:LatexBox_eq_env_patterns . '\)\*\?}\)'
" when s:LatexBox_doc_structure_patterns or g:LatexBox_eq_env_patterns
" are found first, complete math, leave with $ at both sides
let s:eq_dollar_parenthesis_bracket_empty = '$'
let s:eq_pos = cursor_single_dollar
break
elseif line =~ notcomment . '\\begin\s*{\(' . g:LatexBox_eq_env_patterns . '\)\*\?}'
" g:LatexBox_eq_env_patterns is found, complete math, remove $
let s:eq_dollar_parenthesis_bracket_empty = ''
let s:eq_pos = cursor_single_dollar - 1
break
endif
let lnum -= 1
endwhile
return 1
else
" no $ is found, then search for \( or \[ in current line
" 1, whether there is \(
call cursor(lnum_saved, cnum_saved)
let cnum_parenthesis_close = searchpos('\\)', 'cbW', lnum_saved)[1]
let cnum_parenthesis_open = matchend(line_start_2_cnum_saved, '\\(', cnum_parenthesis_close)
if cnum_parenthesis_open >= 0
let s:eq_dollar_parenthesis_bracket_empty = '\)'
let s:eq_pos = cnum_parenthesis_open
return 1
end
" 2, whether there is \[
call cursor(lnum_saved, cnum_saved)
let cnum_bracket_close = searchpos('\\\]', 'cbW', lnum_saved)[1]
let cnum_bracket_open = matchend(line_start_2_cnum_saved, '\\\[', cnum_bracket_close)
if cnum_bracket_open >= 0
let s:eq_dollar_parenthesis_bracket_empty = '\]'
let s:eq_pos = cnum_bracket_open
return 1
end
" not inline math completion
return 0
endif
endfunction
" }}}
" Complete inline euqation{{{
function! s:LatexBox_inlineMath_completion(regex, ...)
if a:0 == 0
let file = LatexBox_GetMainTexFile()
else
let file = a:1
endif
if empty(glob(file, 1))
return ''
endif
if empty(s:eq_dollar_parenthesis_bracket_empty)
let inline_pattern1 = '\$\s*\(' . escape(substitute(a:regex[1:], '^\s\+', '', ""), '\.*^') . '[^$]*\)\s*\$'
let inline_pattern2 = '\\(\s*\(' . escape(substitute(a:regex[1:], '^\s\+', '', ""), '\.*^') . '.*\)\s*\\)'
else
let inline_pattern1 = '\$\s*\(' . escape(substitute(a:regex, '^\s\+', '', ""), '\.*^') . '[^$]*\)\s*\$'
let inline_pattern2 = '\\(\s*\(' . escape(substitute(a:regex, '^\s\+', '', ""), '\.*^') . '.*\)\s*\\)'
endif
let suggestions = []
let line_num = 0
for line in readfile(file)
let line_num = line_num + 1
let suggestions += s:LatexBox_inlineMath_mathlist(line,inline_pattern1 , line_num) + s:LatexBox_inlineMath_mathlist( line,inline_pattern2, line_num)
" search for included files
let included_file = matchstr(line, '^\\@input{\zs[^}]*\ze}')
if included_file != ''
let included_file = LatexBox_kpsewhich(included_file)
call extend(suggestions, s:LatexBox_inlineMath_completion(a:regex, included_file))
endif
endfor
return suggestions
endfunction
" }}}
" Search for inline maths {{{
" search for $ ... $ and \( ... \) in each line
function! s:LatexBox_inlineMath_mathlist(line,inline_pattern, line_num)
let col_start = 0
let suggestions = []
while 1
let matches = matchlist(a:line, a:inline_pattern, col_start)
if !empty(matches)
" show line number of inline math
let entry = {'word': matches[1], 'menu': '[' . a:line_num . ']'}
if s:eq_dollar_parenthesis_bracket_empty != ''
let entry = copy(entry)
let entry.abbr = entry.word
let entry.word = entry.word . s:eq_dollar_parenthesis_bracket_empty
endif
call add(suggestions, entry)
" update col_start
let col_start = matchend(a:line, a:inline_pattern, col_start)
else
break
endif
endwhile
return suggestions
endfunction
" }}}
" Close Current Environment {{{
function! s:CloseCurEnv()
" first, try with \left/\right pairs
let [lnum, cnum] = searchpairpos('\C\\left\>', '', '\C\\right\>', 'bnW', 'LatexBox_InComment()')
if lnum
let line = strpart(getline(lnum), cnum - 1)
let bracket = matchstr(line, '^\\left\zs\((\|\[\|\\{\||\|\.\)\ze')
for [open, close] in [['(', ')'], ['\[', '\]'], ['\\{', '\\}'], ['|', '|'], ['\.', '|']]
let bracket = substitute(bracket, open, close, 'g')
endfor
return '\right' . bracket
endif
" second, try with environments
let env = LatexBox_GetCurrentEnvironment()
if env == '\['
return '\]'
elseif env == '\('
return '\)'
elseif env != ''
return '\end{' . env . '}'
endif
return ''
endfunction
" }}}
" Wrap Selection {{{
function! s:WrapSelection(wrapper)
keepjumps normal! `>a}
execute 'keepjumps normal! `<i\' . a:wrapper . '{'
endfunction
" }}}
" Wrap Selection in Environment with Prompt {{{
function! s:PromptEnvWrapSelection(...)
let env = input('environment: ', '', 'customlist,' . s:SIDWrap('GetEnvironmentList'))
if empty(env)
return
endif
" LaTeXBox's custom indentation can interfere with environment
" insertion when environments are indented (common for nested
" environments). Temporarily disable it for this operation:
let ieOld = &indentexpr
setlocal indentexpr=""
if visualmode() ==# 'V'
execute 'keepjumps normal! `>o\end{' . env . '}'
execute 'keepjumps normal! `<O\begin{' . env . '}'
" indent and format, if requested.
if a:0 && a:1
normal! gv>
normal! gvgq
endif
else
execute 'keepjumps normal! `>a\end{' . env . '}'
execute 'keepjumps normal! `<i\begin{' . env . '}'
endif
exe "setlocal indentexpr=" . ieOld
endfunction
" }}}
" Change Environment {{{
function! s:ChangeEnvPrompt()
let [env, lnum, cnum, lnum2, cnum2] = LatexBox_GetCurrentEnvironment(1)
let new_env = input('change ' . env . ' for: ', '', 'customlist,' . s:SIDWrap('GetEnvironmentList'))
if empty(new_env)
return
endif
if new_env == '\[' || new_env == '['
let begin = '\['
let end = '\]'
elseif new_env == '\(' || new_env == '('
let begin = '\('
let end = '\)'
else
let l:begin = '\begin{' . new_env . '}'
let l:end = '\end{' . new_env . '}'
endif
if env == '\[' || env == '\('
let line = getline(lnum2)
let line = strpart(line, 0, cnum2 - 1) . l:end . strpart(line, cnum2 + 1)
call setline(lnum2, line)
let line = getline(lnum)
let line = strpart(line, 0, cnum - 1) . l:begin . strpart(line, cnum + 1)
call setline(lnum, line)
else
let line = getline(lnum2)
let line = strpart(line, 0, cnum2 - 1) . l:end . strpart(line, cnum2 + len(env) + 5)
call setline(lnum2, line)
let line = getline(lnum)
let line = strpart(line, 0, cnum - 1) . l:begin . strpart(line, cnum + len(env) + 7)
call setline(lnum, line)
endif
endfunction
function! s:GetEnvironmentList(lead, cmdline, pos)
let suggestions = []
for entry in g:LatexBox_completion_environments
let env = entry.word
if env =~ '^' . a:lead
call add(suggestions, env)
endif
endfor
return suggestions
endfunction
function! s:LatexToggleStarEnv()
let [env, lnum, cnum, lnum2, cnum2] = LatexBox_GetCurrentEnvironment(1)
if env == '\('
return
elseif env == '\['
let begin = '\begin{equation}'
let end = '\end{equation}'
elseif env[-1:] == '*'
let begin = '\begin{' . env[:-2] . '}'
let end = '\end{' . env[:-2] . '}'
else
let begin = '\begin{' . env . '*}'
let end = '\end{' . env . '*}'
endif
if env == '\['
let line = getline(lnum2)
let line = strpart(line, 0, cnum2 - 1) . l:end . strpart(line, cnum2 + 1)
call setline(lnum2, line)
let line = getline(lnum)
let line = strpart(line, 0, cnum - 1) . l:begin . strpart(line, cnum + 1)
call setline(lnum, line)
else
let line = getline(lnum2)
let line = strpart(line, 0, cnum2 - 1) . l:end . strpart(line, cnum2 + len(env) + 5)
call setline(lnum2, line)
let line = getline(lnum)
let line = strpart(line, 0, cnum - 1) . l:begin . strpart(line, cnum + len(env) + 7)
call setline(lnum, line)
endif
endfunction
" }}}
" Next Charaters Match {{{
function! s:NextCharsMatch(regex)
let rest_of_line = strpart(getline('.'), col('.') - 1)
return rest_of_line =~ a:regex
endfunction
" }}}
" Mappings {{{
inoremap <silent> <Plug>LatexCloseCurEnv <C-R>=<SID>CloseCurEnv()<CR>
vnoremap <silent> <Plug>LatexWrapSelection :<c-u>call <SID>WrapSelection('')<CR>i
vnoremap <silent> <Plug>LatexEnvWrapSelection :<c-u>call <SID>PromptEnvWrapSelection()<CR>
vnoremap <silent> <Plug>LatexEnvWrapFmtSelection :<c-u>call <SID>PromptEnvWrapSelection(1)<CR>
nnoremap <silent> <Plug>LatexChangeEnv :call <SID>ChangeEnvPrompt()<CR>
nnoremap <silent> <Plug>LatexToggleStarEnv :call <SID>LatexToggleStarEnv()<CR>
" }}}
" vim:fdm=marker:ff=unix:noet:ts=4:sw=4

View File

@@ -0,0 +1,64 @@
" Tex_GetMainFileName: gets the name of the main file being compiled. {{{
" Description: returns the full path name of the main file.
" This function checks for the existence of a .latexmain file
" which might point to the location of a "main" latex file.
" If .latexmain exists, then return the full path name of the
" file being pointed to by it.
"
" Otherwise, return the full path name of the current buffer.
"
" You can supply an optional "modifier" argument to the
" function, which will optionally modify the file name before
" returning.
" NOTE: From version 1.6 onwards, this function always trims
" away the .latexmain part of the file name before applying the
" modifier argument.
function! Tex_GetMainFileName(...)
if a:0 > 0
let modifier = a:1
else
let modifier = ':p'
endif
let s:origdir = fnameescape(getcwd())
let dirmodifier = '%:p:h'
let dirLast = fnameescape(expand(dirmodifier))
exe 'cd '.dirLast
" move up the directory tree until we find a .latexmain file.
" TODO: Should we be doing this recursion by default, or should there be a
" setting?
while glob('*.latexmain') == ''
let dirmodifier = dirmodifier.':h'
let dirNew = fnameescape(expand(dirmodifier))
" break from the loop if we cannot go up any further.
if dirNew == dirLast
break
endif
let dirLast = dirNew
exe 'cd '.dirLast
endwhile
let lheadfile = glob('*.latexmain')
if lheadfile != ''
" Remove the trailing .latexmain part of the filename... We never want
" that.
let lheadfile = fnamemodify(substitute(lheadfile, '\.latexmain$', '', ''), modifier)
else
" If we cannot find any main file, just modify the filename of the
" current buffer.
let lheadfile = expand('%'.modifier)
endif
if lheadfile !~ '\.tex$'
let lheadfile .= '.tex'
endif
exe 'cd '.s:origdir
" NOTE: The caller of this function needs to escape the file name with
" fnameescape() . The reason its not done here is that escaping is not
" safe if this file is to be used as part of an external command on
" certain platforms.
return lheadfile
endfunction

View File

@@ -0,0 +1,319 @@
" Folding support for LaTeX
"
" Options
" g:LatexBox_Folding - Turn on/off folding
" g:LatexBox_fold_preamble - Turn on/off folding of preamble
" g:LatexBox_fold_parts - Define parts (eq. appendix, frontmatter) to fold
" g:LatexBox_fold_sections - Define section levels to fold
" g:LatexBox_fold_envs - Turn on/off folding of environments
"
" {{{1 Set options
if exists('g:LatexBox_Folding') && g:LatexBox_Folding == 1
setl foldmethod=expr
setl foldexpr=LatexBox_FoldLevel(v:lnum)
setl foldtext=LatexBox_FoldText()
"
" The foldexpr function returns "=" for most lines, which means it can become
" slow for large files. The following is a hack that is based on this reply to
" a discussion on the Vim Developer list:
" http://permalink.gmane.org/gmane.editors.vim.devel/14100
"
augroup FastFold
autocmd!
autocmd InsertEnter *.tex setlocal foldmethod=manual
autocmd InsertLeave *.tex setlocal foldmethod=expr
augroup end
endif
if !exists('g:LatexBox_fold_preamble')
let g:LatexBox_fold_preamble=1
endif
if !exists('g:LatexBox_fold_envs')
let g:LatexBox_fold_envs=1
endif
if !exists('g:LatexBox_fold_parts')
let g:LatexBox_fold_parts=[
\ "appendix",
\ "frontmatter",
\ "mainmatter",
\ "backmatter"
\ ]
endif
if !exists('g:LatexBox_fold_sections')
let g:LatexBox_fold_sections=[
\ "part",
\ "chapter",
\ "section",
\ "subsection",
\ "subsubsection"
\ ]
endif
if !exists('g:LatexBox_fold_toc')
let g:LatexBox_fold_toc=0
endif
if !exists('g:LatexBox_fold_toc_levels')
let g:LatexBox_fold_toc_levels=1
endif
" {{{1 LatexBox_FoldLevel help functions
" This function parses the tex file to find the sections that are to be folded
" and their levels, and then predefines the patterns for optimized folding.
function! s:FoldSectionLevels()
" Initialize
let level = 1
let foldsections = []
" If we use two or more of the *matter commands, we need one more foldlevel
let nparts = 0
for part in g:LatexBox_fold_parts
let i = 1
while i < line("$")
if getline(i) =~ '^\s*\\' . part . '\>'
let nparts += 1
break
endif
let i += 1
endwhile
if nparts > 1
let level = 2
break
endif
endfor
" Combine sections and levels, but ignore unused section commands: If we
" don't use the part command, then chapter should have the highest
" level. If we don't use the chapter command, then section should be the
" highest level. And so on.
let ignore = 1
for part in g:LatexBox_fold_sections
" For each part, check if it is used in the file. We start adding the
" part patterns to the fold sections array whenever we find one.
let partpattern = '^\s*\(\\\|% Fake\)' . part . '\>'
if ignore
let i = 1
while i < line("$")
if getline(i) =~# partpattern
call insert(foldsections, [partpattern, level])
let level += 1
let ignore = 0
break
endif
let i += 1
endwhile
else
call insert(foldsections, [partpattern, level])
let level += 1
endif
endfor
return foldsections
endfunction
" {{{1 LatexBox_FoldLevel
" Parse file to dynamically set the sectioning fold levels
let b:LatexBox_FoldSections = s:FoldSectionLevels()
" Optimize by predefine common patterns
let s:notbslash = '\%(\\\@<!\%(\\\\\)*\)\@<='
let s:notcomment = '\%(\%(\\\@<!\%(\\\\\)*\)\@<=%.*\)\@<!'
let s:envbeginpattern = s:notcomment . s:notbslash . '\\begin\s*{.\{-}}'
let s:envendpattern = s:notcomment . s:notbslash . '\\end\s*{.\{-}}'
let s:foldparts = '^\s*\\\%(' . join(g:LatexBox_fold_parts, '\|') . '\)'
let s:folded = '\(% Fake\|\\\(document\|begin\|end\|'
\ . 'front\|main\|back\|app\|sub\|section\|chapter\|part\)\)'
function! LatexBox_FoldLevel(lnum)
" Check for normal lines first (optimization)
let line = getline(a:lnum)
if line !~ s:folded
return "="
endif
" Fold preamble
if g:LatexBox_fold_preamble == 1
if line =~# '\s*\\documentclass'
return ">1"
elseif line =~# '^\s*\\begin\s*{\s*document\s*}'
return "0"
endif
endif
" Fold parts (\frontmatter, \mainmatter, \backmatter, and \appendix)
if line =~# s:foldparts
return ">1"
endif
" Fold chapters and sections
for [part, level] in b:LatexBox_FoldSections
if line =~# part
return ">" . level
endif
endfor
" Never fold \end{document}
if line =~# '^\s*\\end{document}'
return 0
endif
" Fold environments
if g:LatexBox_fold_envs == 1
if line =~# s:envbeginpattern
return "a1"
elseif line =~# s:envendpattern
return "s1"
endif
endif
" Return foldlevel of previous line
return "="
endfunction
" {{{1 LatexBox_FoldText help functions
function! s:LabelEnv()
let i = v:foldend
while i >= v:foldstart
if getline(i) =~ '^\s*\\label'
return matchstr(getline(i), '^\s*\\label{\zs.*\ze}')
end
let i -= 1
endwhile
return ""
endfunction
function! s:CaptionEnv()
let i = v:foldend
while i >= v:foldstart
if getline(i) =~ '^\s*\\caption'
return matchstr(getline(i), '^\s*\\caption\(\[.*\]\)\?{\zs.\+')
end
let i -= 1
endwhile
return ""
endfunction
function! s:CaptionTable()
let i = v:foldstart
while i <= v:foldend
if getline(i) =~ '^\s*\\caption'
return matchstr(getline(i), '^\s*\\caption\(\[.*\]\)\?{\zs.\+')
end
let i += 1
endwhile
return ""
endfunction
function! s:CaptionFrame(line)
" Test simple variants first
let caption1 = matchstr(a:line,'\\begin\*\?{.*}{\zs.\+\ze}')
let caption2 = matchstr(a:line,'\\begin\*\?{.*}{\zs.\+')
if len(caption1) > 0
return caption1
elseif len(caption2) > 0
return caption2
else
let i = v:foldstart
while i <= v:foldend
if getline(i) =~ '^\s*\\frametitle'
return matchstr(getline(i),
\ '^\s*\\frametitle\(\[.*\]\)\?{\zs.\+')
end
let i += 1
endwhile
return ""
endif
endfunction
" {{{1 LatexBox_FoldText
function! LatexBox_FoldText()
" Initialize
let line = getline(v:foldstart)
let nlines = v:foldend - v:foldstart + 1
let level = ''
let title = 'Not defined'
" Fold level
let level = strpart(repeat('-', v:foldlevel-1) . '*',0,3)
if v:foldlevel > 3
let level = strpart(level, 1) . v:foldlevel
endif
let level = printf('%-3s', level)
" Preamble
if line =~ '\s*\\documentclass'
let title = "Preamble"
endif
" Parts, sections and fakesections
let sections = '\(\(sub\)*section\|part\|chapter\)'
let secpat1 = '^\s*\\' . sections . '\*\?\s*{'
let secpat2 = '^\s*\\' . sections . '\*\?\s*\['
if line =~ '\\frontmatter'
let title = "Frontmatter"
elseif line =~ '\\mainmatter'
let title = "Mainmatter"
elseif line =~ '\\backmatter'
let title = "Backmatter"
elseif line =~ '\\appendix'
let title = "Appendix"
elseif line =~ secpat1 . '.*}'
let title = matchstr(line, secpat1 . '\zs.*\ze}')
elseif line =~ secpat1
let title = matchstr(line, secpat1 . '\zs.*')
elseif line =~ secpat2 . '.*\]'
let title = matchstr(line, secpat2 . '\zs.*\ze\]')
elseif line =~ secpat2
let title = matchstr(line, secpat2 . '\zs.*')
elseif line =~ 'Fake' . sections . ':'
let title = matchstr(line,'Fake' . sections . ':\s*\zs.*')
elseif line =~ 'Fake' . sections
let title = matchstr(line, 'Fake' . sections)
endif
" Environments
if line =~ '\\begin'
" Capture environment name
let env = matchstr(line,'\\begin\*\?{\zs\w*\*\?\ze}')
" Set caption based on type of environment
if env == 'frame'
let label = ''
let caption = s:CaptionFrame(line)
elseif env == 'table'
let label = s:LabelEnv()
let caption = s:CaptionTable()
else
let label = s:LabelEnv()
let caption = s:CaptionEnv()
endif
" If no caption found, check for a caption comment
if caption == ''
let caption = matchstr(line,'\\begin\*\?{.*}\s*%\s*\zs.*')
endif
" Create title based on caption and label
if caption . label == ''
let title = env
elseif label == ''
let title = printf('%-12s%s', env . ':',
\ substitute(caption, '}\s*$', '',''))
elseif caption == ''
let title = printf('%-12s%56s', env, '(' . label . ')')
else
let title = printf('%-12s%-30s %21s', env . ':',
\ strpart(substitute(caption, '}\s*$', '',''),0,34),
\ '(' . label . ')')
endif
endif
let title = strpart(title, 0, 68)
return printf('%-3s %-68s #%5d', level, title, nlines)
endfunction
" {{{1 Footer
" vim:fdm=marker:ff=unix:ts=4:sw=4

View File

@@ -0,0 +1,500 @@
" LaTeX Box latexmk functions
" Options and variables {{{
if !exists('g:LatexBox_latexmk_options')
let g:LatexBox_latexmk_options = ''
endif
if !exists('g:LatexBox_latexmk_env')
let g:LatexBox_latexmk_env = ''
endif
if !exists('g:LatexBox_latexmk_async')
let g:LatexBox_latexmk_async = 0
endif
if !exists('g:LatexBox_latexmk_preview_continuously')
let g:LatexBox_latexmk_preview_continuously = 0
endif
if !exists('g:LatexBox_output_type')
let g:LatexBox_output_type = 'pdf'
endif
if !exists('g:LatexBox_autojump')
let g:LatexBox_autojump = 0
endif
if ! exists('g:LatexBox_quickfix')
let g:LatexBox_quickfix = 1
endif
" }}}
" Process ID management (used for asynchronous and continuous mode) {{{
" A dictionary of latexmk PID's (basename: pid)
if !exists('g:latexmk_running_pids')
let g:latexmk_running_pids = {}
endif
" Set PID {{{
function! s:LatexmkSetPID(basename, pid)
let g:latexmk_running_pids[a:basename] = a:pid
endfunction
" }}}
" kill_latexmk_process {{{
function! s:kill_latexmk_process(pid)
if has('win32')
silent execute '!taskkill /PID ' . a:pid . ' /T /F'
else
if g:LatexBox_latexmk_async
" vim-server mode
let pids = []
let tmpfile = tempname()
silent execute '!ps x -o pgid,pid > ' . tmpfile
for line in readfile(tmpfile)
let new_pid = matchstr(line, '^\s*' . a:pid . '\s\+\zs\d\+\ze')
if !empty(new_pid)
call add(pids, new_pid)
endif
endfor
call delete(tmpfile)
if !empty(pids)
silent execute '!kill ' . join(pids)
endif
else
" single background process
silent execute '!kill ' . a:pid
endif
endif
if !has('gui_running')
redraw!
endif
endfunction
" }}}
" kill_all_latexmk_processes {{{
function! s:kill_all_latexmk_processes()
for pid in values(g:latexmk_running_pids)
call s:kill_latexmk_process(pid)
endfor
endfunction
" }}}
" }}}
" Setup for vim-server {{{
function! s:SIDWrap(func)
if !exists('s:SID')
let s:SID = matchstr(expand('<sfile>'), '\zs<SNR>\d\+_\ze.*$')
endif
return s:SID . a:func
endfunction
function! s:LatexmkCallback(basename, status)
" Only remove the pid if not in continuous mode
if !g:LatexBox_latexmk_preview_continuously
call remove(g:latexmk_running_pids, a:basename)
endif
call LatexBox_LatexErrors(a:status, a:basename)
endfunction
function! s:setup_vim_server()
if !exists('g:vim_program')
" attempt autodetection of vim executable
let g:vim_program = ''
if has('win32')
" Just drop through to the default for windows
else
if match(&shell, '\(bash\|zsh\)$') >= 0
let ppid = '$PPID'
else
let ppid = '$$'
endif
let tmpfile = tempname()
silent execute '!ps -o command= -p ' . ppid . ' > ' . tmpfile
for line in readfile(tmpfile)
let line = matchstr(line, '^\S\+\>')
if !empty(line) && executable(line)
let g:vim_program = line . ' -g'
break
endif
endfor
call delete(tmpfile)
endif
if empty(g:vim_program)
if has('gui_macvim')
let g:vim_program
\ = '/Applications/MacVim.app/Contents/MacOS/Vim -g'
else
let g:vim_program = v:progname
endif
endif
endif
endfunction
" }}}
" Latexmk {{{
function! LatexBox_Latexmk(force)
" Define often used names
let basepath = LatexBox_GetTexBasename(1)
let basename = fnamemodify(basepath, ':t')
let texroot = shellescape(LatexBox_GetTexRoot())
let mainfile = fnameescape(fnamemodify(LatexBox_GetMainTexFile(), ':t'))
" Check if latexmk is installed
if !executable('latexmk')
echomsg "Error: LaTeX-Box relies on latexmk for compilation, but it" .
\ " is not installed!"
return
endif
" Check if already running
if has_key(g:latexmk_running_pids, basepath)
echomsg "latexmk is already running for `" . basename . "'"
return
endif
" Set wrap width in log file
let max_print_line = 2000
if has('win32')
let env = 'set max_print_line=' . max_print_line . ' & '
elseif match(&shell, '/tcsh$') >= 0
let env = 'setenv max_print_line ' . max_print_line . '; '
else
let env = 'max_print_line=' . max_print_line
endif
" Set environment options
let env .= ' ' . g:LatexBox_latexmk_env . ' '
" Set latexmk command with options
if has('win32')
" Make sure to switch drive as well as directory
let cmd = 'cd /D ' . texroot . ' && '
else
let cmd = 'cd ' . texroot . ' && '
endif
let cmd .= env . ' latexmk'
let cmd .= ' -' . g:LatexBox_output_type
let cmd .= ' -quiet '
let cmd .= g:LatexBox_latexmk_options
if a:force
let cmd .= ' -g'
endif
if g:LatexBox_latexmk_preview_continuously
let cmd .= ' -pvc'
endif
let cmd .= ' -e ' . shellescape('$pdflatex =~ s/ / -file-line-error /')
let cmd .= ' -e ' . shellescape('$latex =~ s/ / -file-line-error /')
if g:LatexBox_latexmk_preview_continuously
let cmd .= ' -e ' . shellescape('$success_cmd = $ENV{SUCCESSCMD}')
let cmd .= ' -e ' . shellescape('$failure_cmd = $ENV{FAILURECMD}')
endif
let cmd .= ' ' . mainfile
" Redirect output to null
if has('win32')
let cmd .= ' >nul'
else
let cmd .= ' &>/dev/null'
endif
if g:LatexBox_latexmk_async
" Check if VIM server exists
if empty(v:servername)
echoerr "cannot run latexmk in background without a VIM server"
echoerr "set g:LatexBox_latexmk_async to 0 to change compiling mode"
return
endif
" Start vim server if necessary
call s:setup_vim_server()
let setpidfunc = s:SIDWrap('LatexmkSetPID')
let callbackfunc = s:SIDWrap('LatexmkCallback')
if has('win32')
let vim_program = substitute(g:vim_program,
\ 'gvim\.exe$', 'vim.exe', '')
" Define callback to set the pid
let callsetpid = setpidfunc . '(''' . basepath . ''', %CMDPID%)'
let vimsetpid = vim_program . ' --servername ' . v:servername
\ . ' --remote-expr ' . shellescape(callsetpid)
" Define callback after latexmk is finished
let callback = callbackfunc . '(''' . basepath . ''', %LATEXERR%)'
let vimcmd = vim_program . ' --servername ' . v:servername
\ . ' --remote-expr ' . shellescape(callback)
let scallback = callbackfunc . '(''' . basepath . ''', 0)'
let svimcmd = vim_program . ' --servername ' . v:servername
\ . ' --remote-expr ' . shellescape(scallback)
let fcallback = callbackfunc . '(''' . basepath . ''', 1)'
let fvimcmd = vim_program . ' --servername ' . v:servername
\ . ' --remote-expr ' . shellescape(fcallback)
let asyncbat = tempname() . '.bat'
if g:LatexBox_latexmk_preview_continuously
call writefile(['setlocal',
\ 'set T=%TEMP%\sthUnique.tmp',
\ 'wmic process where (Name="WMIC.exe" AND CommandLine LIKE "%%%TIME%%%") '
\ . 'get ParentProcessId /value | find "ParentProcessId" >%T%',
\ 'set /P A=<%T%',
\ 'set CMDPID=%A:~16% & del %T%',
\ vimsetpid,
\ 'set SUCCESSCMD='.svimcmd,
\ 'set FAILURECMD='.fvimcmd,
\ cmd,
\ 'endlocal'], asyncbat)
else
call writefile(['setlocal',
\ 'set T=%TEMP%\sthUnique.tmp',
\ 'wmic process where (Name="WMIC.exe" AND CommandLine LIKE "%%%TIME%%%") '
\ . 'get ParentProcessId /value | find "ParentProcessId" >%T%',
\ 'set /P A=<%T%',
\ 'set CMDPID=%A:~16% & del %T%',
\ vimsetpid,
\ cmd,
\ 'set LATEXERR=%ERRORLEVEL%',
\ vimcmd,
\ 'endlocal'], asyncbat)
endif
" Define command
let cmd = '!start /b ' . asyncbat . ' & del ' . asyncbat
else
" Define callback to set the pid
let callsetpid = shellescape(setpidfunc).'"(\"'.basepath.'\",$$)"'
let vimsetpid = g:vim_program . ' --servername ' . v:servername
\ . ' --remote-expr ' . callsetpid
" Define callback after latexmk is finished
let callback = shellescape(callbackfunc).'"(\"'.basepath.'\",$?)"'
let vimcmd = g:vim_program . ' --servername ' . v:servername
\ . ' --remote-expr ' . callback
let scallback = shellescape(callbackfunc).'"(\"'.basepath.'\",0)"'
let svimcmd = g:vim_program . ' --servername ' . v:servername
\ . ' --remote-expr ' . scallback
let fcallback = shellescape(callbackfunc).'"(\"'.basepath.'\",1)"'
let fvimcmd = g:vim_program . ' --servername ' . v:servername
\ . ' --remote-expr ' . fcallback
" Define command
" Note: Here we escape '%' because it may be given as a user option
" through g:LatexBox_latexmk_options, for instance with
" g:Latex..._options = "-pdflatex='pdflatex -synctex=1 \%O \%S'"
if g:LatexBox_latexmk_preview_continuously
let cmd = vimsetpid . ' ; '
\ . 'export SUCCESSCMD=' . shellescape(svimcmd) . ' '
\ . ' FAILURECMD=' . shellescape(fvimcmd) . ' ; '
\ . escape(cmd, '%')
else
let cmd = vimsetpid . ' ; ' . escape(cmd, '%') . ' ; ' . vimcmd
endif
let cmd = '! (' . cmd . ') >/dev/null &'
endif
if g:LatexBox_latexmk_preview_continuously
echo 'Compiling to ' . g:LatexBox_output_type
\ . ' with continuous preview.'
else
echo 'Compiling to ' . g:LatexBox_output_type . ' ...'
endif
silent execute cmd
else
if g:LatexBox_latexmk_preview_continuously
if has('win32')
let cmd = '!start /b cmd /s /c "' . cmd . '"'
else
let cmd = '!' . cmd . ' &'
endif
echo 'Compiling to ' . g:LatexBox_output_type . ' ...'
silent execute cmd
" Save PID in order to be able to kill the process when wanted.
if has('win32')
let tmpfile = tempname()
let pidcmd = 'cmd /c "wmic process where '
\ . '(CommandLine LIKE "latexmk\%'.mainfile.'\%") '
\ . 'get ProcessId /value | find "ProcessId" '
\ . '>'.tmpfile.' "'
silent execute '! ' . pidcmd
let pids = readfile(tmpfile)
let pid = strpart(pids[0], 10)
let g:latexmk_running_pids[basepath] = pid
else
let pid = substitute(system('pgrep -f "perl.*'
\ . mainfile . '" | head -n 1'),'\D','','')
let g:latexmk_running_pids[basepath] = pid
endif
else
" Execute command and check for errors
echo 'Compiling to ' . g:LatexBox_output_type . ' ... (async off!)'
call system(cmd)
call LatexBox_LatexErrors(v:shell_error)
endif
endif
" Redraw screen if necessary
if !has("gui_running")
redraw!
endif
endfunction
" }}}
" LatexmkClean {{{
function! LatexBox_LatexmkClean(cleanall)
" Check if latexmk is installed
if !executable('latexmk')
echomsg "Error: LaTeX-Box relies on latexmk for compilation, but it" .
\ " is not installed!"
return
endif
let basename = LatexBox_GetTexBasename(1)
if has_key(g:latexmk_running_pids, basename)
echomsg "don't clean when latexmk is running"
return
endif
if has('win32')
let cmd = 'cd /D ' . shellescape(LatexBox_GetTexRoot()) . ' & '
else
let cmd = 'cd ' . shellescape(LatexBox_GetTexRoot()) . ';'
endif
if a:cleanall
let cmd .= 'latexmk -C '
else
let cmd .= 'latexmk -c '
endif
let cmd .= shellescape(LatexBox_GetMainTexFile())
if has('win32')
let cmd .= ' >nul'
else
let cmd .= ' >&/dev/null'
endif
call system(cmd)
if !has('gui_running')
redraw!
endif
echomsg "latexmk clean finished"
endfunction
" }}}
" LatexErrors {{{
function! LatexBox_LatexErrors(status, ...)
if a:0 >= 1
let log = a:1 . '.log'
else
let log = LatexBox_GetLogFile()
endif
cclose
" set cwd to expand error file correctly
let l:cwd = fnamemodify(getcwd(), ':p')
execute 'lcd ' . fnameescape(LatexBox_GetTexRoot())
try
if g:LatexBox_autojump
execute 'cfile ' . fnameescape(log)
else
execute 'cgetfile ' . fnameescape(log)
endif
finally
" restore cwd
execute 'lcd ' . fnameescape(l:cwd)
endtry
" Always open window if started by LatexErrors command
if a:status < 0
botright copen
else
" Write status message to screen
redraw
if a:status > 0 || len(getqflist())>1
echomsg 'Compiling to ' . g:LatexBox_output_type . ' ... failed!'
else
echomsg 'Compiling to ' . g:LatexBox_output_type . ' ... success!'
endif
" Only open window when an error/warning is detected
if g:LatexBox_quickfix
belowright cw
if g:LatexBox_quickfix==2
wincmd p
endif
endif
endif
endfunction
" }}}
" LatexmkStatus {{{
function! LatexBox_LatexmkStatus(detailed)
if a:detailed
if empty(g:latexmk_running_pids)
echo "latexmk is not running"
else
let plist = ""
for [basename, pid] in items(g:latexmk_running_pids)
if !empty(plist)
let plist .= '; '
endif
let plist .= fnamemodify(basename, ':t') . ':' . pid
endfor
echo "latexmk is running (" . plist . ")"
endif
else
let basename = LatexBox_GetTexBasename(1)
if has_key(g:latexmk_running_pids, basename)
echo "latexmk is running"
else
echo "latexmk is not running"
endif
endif
endfunction
" }}}
" LatexmkStop {{{
function! LatexBox_LatexmkStop(silent)
if empty(g:latexmk_running_pids)
if !a:silent
let basepath = LatexBox_GetTexBasename(1)
let basename = fnamemodify(basepath, ':t')
echoerr "latexmk is not running for `" . basename . "'"
endif
else
let basepath = LatexBox_GetTexBasename(1)
let basename = fnamemodify(basepath, ':t')
if has_key(g:latexmk_running_pids, basepath)
call s:kill_latexmk_process(g:latexmk_running_pids[basepath])
call remove(g:latexmk_running_pids, basepath)
if !a:silent
echomsg "latexmk stopped for `" . basename . "'"
endif
elseif !a:silent
echoerr "latexmk is not running for `" . basename . "'"
endif
endif
endfunction
" }}}
" Commands {{{
command! -bang Latexmk call LatexBox_Latexmk(<q-bang> == "!")
command! -bang LatexmkClean call LatexBox_LatexmkClean(<q-bang> == "!")
command! -bang LatexmkStatus call LatexBox_LatexmkStatus(<q-bang> == "!")
command! LatexmkStop call LatexBox_LatexmkStop(0)
command! LatexErrors call LatexBox_LatexErrors(-1)
if g:LatexBox_latexmk_async || g:LatexBox_latexmk_preview_continuously
autocmd BufUnload <buffer> call LatexBox_LatexmkStop(1)
autocmd VimLeave * call <SID>kill_all_latexmk_processes()
endif
" }}}
" vim:fdm=marker:ff=unix:noet:ts=4:sw=4

View File

@@ -0,0 +1,96 @@
" LaTeX Box mappings
if exists("g:LatexBox_no_mappings")
finish
endif
" latexmk {{{
map <buffer> <LocalLeader>ll :Latexmk<CR>
map <buffer> <LocalLeader>lL :Latexmk!<CR>
map <buffer> <LocalLeader>lc :LatexmkClean<CR>
map <buffer> <LocalLeader>lC :LatexmkClean!<CR>
map <buffer> <LocalLeader>lg :LatexmkStatus<CR>
map <buffer> <LocalLeader>lG :LatexmkStatus!<CR>
map <buffer> <LocalLeader>lk :LatexmkStop<CR>
map <buffer> <LocalLeader>le :LatexErrors<CR>
" }}}
" View {{{
map <buffer> <LocalLeader>lv :LatexView<CR>
" }}}
" TOC {{{
map <silent> <buffer> <LocalLeader>lt :LatexTOC<CR>
" }}}
" Jump to match {{{
if !exists('g:LatexBox_loaded_matchparen')
nmap <buffer> % <Plug>LatexBox_JumpToMatch
vmap <buffer> % <Plug>LatexBox_JumpToMatch
omap <buffer> % <Plug>LatexBox_JumpToMatch
endif
" }}}
" Define text objects {{{
vmap <buffer> ie <Plug>LatexBox_SelectCurrentEnvInner
vmap <buffer> ae <Plug>LatexBox_SelectCurrentEnvOuter
omap <buffer> ie :normal vie<CR>
omap <buffer> ae :normal vae<CR>
vmap <buffer> i$ <Plug>LatexBox_SelectInlineMathInner
vmap <buffer> a$ <Plug>LatexBox_SelectInlineMathOuter
omap <buffer> i$ :normal vi$<CR>
omap <buffer> a$ :normal va$<CR>
" }}}
" Jump between sections {{{
function! s:LatexBoxNextSection(type, backwards, visual)
" Restore visual mode if desired
if a:visual
normal! gv
endif
" For the [] and ][ commands we move up or down before the search
if a:type == 1
if a:backwards
normal! k
else
normal! j
endif
endif
" Define search pattern and do the search while preserving "/
let save_search = @/
let flags = 'W'
if a:backwards
let flags = 'b' . flags
endif
let notcomment = '\%(\%(\\\@<!\%(\\\\\)*\)\@<=%.*\)\@<!'
let pattern = notcomment . '\v\s*\\(' . join([
\ '(sub)*section',
\ 'chapter',
\ 'part',
\ 'appendix',
\ '(front|back|main)matter'], '|') . ')>'
call search(pattern, flags)
let @/ = save_search
" For the [] and ][ commands we move down or up after the search
if a:type == 1
if a:backwards
normal! j
else
normal! k
endif
endif
endfunction
noremap <buffer> <silent> ]] :call <SID>LatexBoxNextSection(0,0,0)<CR>
noremap <buffer> <silent> ][ :call <SID>LatexBoxNextSection(1,0,0)<CR>
noremap <buffer> <silent> [] :call <SID>LatexBoxNextSection(1,1,0)<CR>
noremap <buffer> <silent> [[ :call <SID>LatexBoxNextSection(0,1,0)<CR>
vnoremap <buffer> <silent> ]] :<c-u>call <SID>LatexBoxNextSection(0,0,1)<CR>
vnoremap <buffer> <silent> ][ :<c-u>call <SID>LatexBoxNextSection(1,0,1)<CR>
vnoremap <buffer> <silent> [] :<c-u>call <SID>LatexBoxNextSection(1,1,1)<CR>
vnoremap <buffer> <silent> [[ :<c-u>call <SID>LatexBoxNextSection(0,1,1)<CR>
" }}}
" vim:fdm=marker:ff=unix:noet:ts=4:sw=4

View File

@@ -0,0 +1,531 @@
" LaTeX Box motion functions
" Motion options {{{
" Opening and closing patterns
if !exists('g:LatexBox_open_pats')
let g:LatexBox_open_pats = [ '\\{','{','\\(','(','\\\[','\[',
\ '\\begin\s*{.\{-}}', '\\left\s*\%([^\\]\|\\.\|\\\a*\)']
let g:LatexBox_close_pats = [ '\\}','}','\\)',')','\\\]','\]',
\ '\\end\s*{.\{-}}', '\\right\s*\%([^\\]\|\\.\|\\\a*\)']
endif
" }}}
" HasSyntax {{{
" s:HasSyntax(syntaxName, [line], [col])
function! s:HasSyntax(syntaxName, ...)
let line = a:0 >= 1 ? a:1 : line('.')
let col = a:0 >= 2 ? a:2 : col('.')
return index(map(synstack(line, col),
\ 'synIDattr(v:val, "name") == "' . a:syntaxName . '"'),
\ 1) >= 0
endfunction
" }}}
" Search and Skip Comments {{{
" s:SearchAndSkipComments(pattern, [flags], [stopline])
function! s:SearchAndSkipComments(pat, ...)
let flags = a:0 >= 1 ? a:1 : ''
let stopline = a:0 >= 2 ? a:2 : 0
let saved_pos = getpos('.')
" search once
let ret = search(a:pat, flags, stopline)
if ret
" do not match at current position if inside comment
let flags = substitute(flags, 'c', '', 'g')
" keep searching while in comment
while LatexBox_InComment()
let ret = search(a:pat, flags, stopline)
if !ret
break
endif
endwhile
endif
if !ret
" if no match found, restore position
call setpos('.', saved_pos)
endif
return ret
endfunction
" }}}
" Finding Matching Pair {{{
function! s:FindMatchingPair(mode)
if a:mode =~ 'h\|i'
2match none
elseif a:mode == 'v'
normal! gv
endif
if LatexBox_InComment() | return | endif
" open/close pairs (dollars signs are treated apart)
let dollar_pat = '\$'
let notbslash = '\%(\\\@<!\%(\\\\\)*\)\@<='
let notcomment = '\%(\%(\\\@<!\%(\\\\\)*\)\@<=%.*\)\@<!'
let anymatch = '\('
\ . join(g:LatexBox_open_pats + g:LatexBox_close_pats, '\|')
\ . '\|' . dollar_pat . '\)'
let lnum = line('.')
let cnum = searchpos('\A', 'cbnW', lnum)[1]
" if the previous char is a backslash
if strpart(getline(lnum), cnum-2, 1) == '\'
let cnum = cnum-1
endif
let delim = matchstr(getline(lnum), '\C^'. anymatch , cnum - 1)
if empty(delim) || strlen(delim)+cnum-1< col('.')
if a:mode =~ 'n\|v\|o'
" if not found, search forward
let cnum = match(getline(lnum), '\C'. anymatch , col('.') - 1) + 1
if cnum == 0 | return | endif
call cursor(lnum, cnum)
let delim = matchstr(getline(lnum), '\C^'. anymatch , cnum - 1)
elseif a:mode =~ 'i'
" if not found, move one char bacward and search
let cnum = searchpos('\A', 'bnW', lnum)[1]
" if the previous char is a backslash
if strpart(getline(lnum), cnum-2, 1) == '\'
let cnum = cnum-1
endif
let delim = matchstr(getline(lnum), '\C^'. anymatch , cnum - 1)
if empty(delim) || strlen(delim)+cnum< col('.') | return | endif
elseif a:mode =~ 'h'
return
endif
endif
if delim =~ '^\$'
" match $-pairs
" check if next character is in inline math
let [lnum0, cnum0] = searchpos('.', 'nW')
if lnum0 && s:HasSyntax('texMathZoneX', lnum0, cnum0)
let [lnum2, cnum2] = searchpos(notcomment . notbslash. dollar_pat, 'nW', line('w$')*(a:mode =~ 'h\|i') , 200)
else
let [lnum2, cnum2] = searchpos('\%(\%'. lnum . 'l\%' . cnum . 'c\)\@!'. notcomment . notbslash . dollar_pat, 'bnW', line('w0')*(a:mode =~ 'h\|i') , 200)
endif
if a:mode =~ 'h\|i'
execute '2match MatchParen /\%(\%' . lnum . 'l\%' . cnum . 'c\$' . '\|\%' . lnum2 . 'l\%' . cnum2 . 'c\$\)/'
elseif a:mode =~ 'n\|v\|o'
call cursor(lnum2,cnum2)
endif
else
" match other pairs
for i in range(len(g:LatexBox_open_pats))
let open_pat = notbslash . g:LatexBox_open_pats[i]
let close_pat = notbslash . g:LatexBox_close_pats[i]
if delim =~# '^' . open_pat
" if on opening pattern, search for closing pattern
let [lnum2, cnum2] = searchpairpos('\C' . open_pat, '', '\C'
\ . close_pat, 'nW', 'LatexBox_InComment()',
\ line('w$')*(a:mode =~ 'h\|i') , 200)
if a:mode =~ 'h\|i'
execute '2match MatchParen /\%(\%' . lnum . 'l\%' . cnum
\ . 'c' . g:LatexBox_open_pats[i] . '\|\%'
\ . lnum2 . 'l\%' . cnum2 . 'c'
\ . g:LatexBox_close_pats[i] . '\)/'
elseif a:mode =~ 'n\|v\|o'
call cursor(lnum2,cnum2)
if strlen(close_pat)>1 && a:mode =~ 'o'
call cursor(lnum2, matchend(getline('.'), '\C'
\ . close_pat, col('.')-1))
endif
endif
break
elseif delim =~# '^' . close_pat
" if on closing pattern, search for opening pattern
let [lnum2, cnum2] = searchpairpos('\C' . open_pat, '',
\ '\C\%(\%'. lnum . 'l\%' . cnum . 'c\)\@!'
\ . close_pat, 'bnW', 'LatexBox_InComment()',
\ line('w0')*(a:mode =~ 'h\|i') , 200)
if a:mode =~ 'h\|i'
execute '2match MatchParen /\%(\%' . lnum2 . 'l\%' . cnum2
\ . 'c' . g:LatexBox_open_pats[i] . '\|\%'
\ . lnum . 'l\%' . cnum . 'c'
\ . g:LatexBox_close_pats[i] . '\)/'
elseif a:mode =~ 'n\|v\|o'
call cursor(lnum2,cnum2)
endif
break
endif
endfor
endif
endfunction
" Allow to disable functionality if desired
if !exists('g:LatexBox_loaded_matchparen')
" Disable matchparen autocommands
augroup LatexBox_HighlightPairs
autocmd BufEnter * if !exists("g:loaded_matchparen") || !g:loaded_matchparen | runtime plugin/matchparen.vim | endif
autocmd BufEnter *.tex 3match none | unlet! g:loaded_matchparen | au! matchparen
autocmd! CursorMoved *.tex call s:FindMatchingPair('h')
autocmd! CursorMovedI *.tex call s:FindMatchingPair('i')
augroup END
endif
" Use LatexBox'es FindMatchingPair as '%' (enable jump between e.g. $'s)
nnoremap <silent> <Plug>LatexBox_JumpToMatch :call <SID>FindMatchingPair('n')<CR>
vnoremap <silent> <Plug>LatexBox_JumpToMatch :call <SID>FindMatchingPair('v')<CR>
onoremap <silent> <Plug>LatexBox_JumpToMatch v:call <SID>FindMatchingPair('o')<CR>
" }}}
" select inline math {{{
" s:SelectInlineMath(seltype)
" where seltype is either 'inner' or 'outer'
function! s:SelectInlineMath(seltype)
let dollar_pat = '\\\@<!\$'
if s:HasSyntax('texMathZoneX')
call s:SearchAndSkipComments(dollar_pat, 'cbW')
elseif getline('.')[col('.') - 1] == '$'
call s:SearchAndSkipComments(dollar_pat, 'bW')
else
return
endif
if a:seltype == 'inner'
normal! l
endif
if visualmode() ==# 'V'
normal! V
else
normal! v
endif
call s:SearchAndSkipComments(dollar_pat, 'W')
if a:seltype == 'inner'
normal! h
endif
endfunction
vnoremap <silent> <Plug>LatexBox_SelectInlineMathInner
\ :<C-U>call <SID>SelectInlineMath('inner')<CR>
vnoremap <silent> <Plug>LatexBox_SelectInlineMathOuter
\ :<C-U>call <SID>SelectInlineMath('outer')<CR>
" }}}
" select current environment {{{
function! s:SelectCurrentEnv(seltype)
let [env, lnum, cnum, lnum2, cnum2] = LatexBox_GetCurrentEnvironment(1)
call cursor(lnum, cnum)
if a:seltype == 'inner'
if env =~ '^\'
call search('\\.\_\s*\S', 'eW')
else
call search('}\(\_\s*\[\_[^]]*\]\)\?\_\s*\S', 'eW')
endif
endif
if visualmode() ==# 'V'
normal! V
else
normal! v
endif
call cursor(lnum2, cnum2)
if a:seltype == 'inner'
call search('\S\_\s*', 'bW')
else
if env =~ '^\'
normal! l
else
call search('}', 'eW')
endif
endif
endfunction
vnoremap <silent> <Plug>LatexBox_SelectCurrentEnvInner :<C-U>call <SID>SelectCurrentEnv('inner')<CR>
vnoremap <silent> <Plug>LatexBox_SelectCurrentEnvOuter :<C-U>call <SID>SelectCurrentEnv('outer')<CR>
" }}}
" Jump to the next braces {{{
"
function! LatexBox_JumpToNextBraces(backward)
let flags = ''
if a:backward
normal h
let flags .= 'b'
else
let flags .= 'c'
endif
if search('[][}{]', flags) > 0
normal l
endif
let prev = strpart(getline('.'), col('.') - 2, 1)
let next = strpart(getline('.'), col('.') - 1, 1)
if next =~ '[]}]' && prev !~ '[][{}]'
return "\<Right>"
else
return ''
endif
endfunction
" }}}
" Table of Contents {{{
" Special UTF-8 conversion
function! s:ConvertBack(line)
let line = a:line
if exists('g:LatexBox_plaintext_toc')
"
" Substitute stuff like '\IeC{\"u}' to plain 'u'
"
let line = substitute(line, '\\IeC\s*{\\.\(.\)}', '\1', 'g')
else
"
" Substitute stuff like '\IeC{\"u}' to corresponding unicode symbols
"
for [pat, symbol] in s:ConvBackPats
let line = substitute(line, pat, symbol, 'g')
endfor
endif
return line
endfunction
function! s:ReadTOC(auxfile, texfile, ...)
let texfile = a:texfile
let prefix = fnamemodify(a:auxfile, ':p:h')
if a:0 != 2
let toc = []
let fileindices = { texfile : [] }
else
let toc = a:1
let fileindices = a:2
let fileindices[ texfile ] = []
endif
for line in readfile(a:auxfile)
let included = matchstr(line, '^\\@input{\zs[^}]*\ze}')
if included != ''
" append the input TOX to `toc` and `fileindices`
let newaux = prefix . '/' . included
let newtex = fnamemodify(newaux, ':r') . '.tex'
call s:ReadTOC(newaux, newtex, toc, fileindices)
continue
endif
" Parse statements like:
" \@writefile{toc}{\contentsline {section}{\numberline {secnum}Section Title}{pagenumber}}
" \@writefile{toc}{\contentsline {section}{\tocsection {}{1}{Section Title}}{pagenumber}}
" \@writefile{toc}{\contentsline {section}{\numberline {secnum}Section Title}{pagenumber}{otherstuff}}
let line = matchstr(line,
\ '\\@writefile{toc}{\\contentsline\s*\zs.*\ze}\s*$')
if empty(line)
continue
endif
let tree = LatexBox_TexToTree(s:ConvertBack(line))
if len(tree) < 3
" unknown entry type: just skip it
continue
endif
" parse level
let level = tree[0][0]
" parse page
if !empty(tree[2])
let page = tree[2][0]
else
let page = ''
endif
" parse section number
let secnum = ''
if len(tree[1]) > 3 && empty(tree[1][1])
call remove(tree[1], 1)
endif
if len(tree[1]) > 1 && tree[1][0] =~ '\(numberline\|tocsection\)'
if !empty(tree[1][1])
let secnum = LatexBox_TreeToTex(tree[1][1])
let secnum = substitute(secnum, '\\\S\+\s', '', 'g')
let secnum = substitute(secnum, '\\\S\+{\(.\{-}\)}', '\1', 'g')
let secnum = substitute(secnum, '^{\+\|}\+$', '', 'g')
endif
let tree = tree[1][2:]
else
let tree = tree[1]
endif
" parse section title
let text = LatexBox_TreeToTex(tree)
let text = substitute(text, '^{\+\|}\+$', '', 'g')
let text = substitute(text, '\*', '', 'g')
" add TOC entry
call add(fileindices[texfile], len(toc))
call add(toc, {'file': texfile,
\ 'level': level,
\ 'number': secnum,
\ 'text': text,
\ 'page': page})
endfor
return [toc, fileindices]
endfunction
function! LatexBox_TOC(...)
" Check if window already exists
let winnr = bufwinnr(bufnr('LaTeX TOC'))
if winnr >= 0
if a:0 == 0
silent execute winnr . 'wincmd w'
else
" Supplying an argument to this function causes toggling instead
" of jumping to the TOC window
if g:LatexBox_split_resize
silent exe "set columns-=" . g:LatexBox_split_width
endif
silent execute 'bwipeout' . bufnr('LaTeX TOC')
endif
return
endif
" Read TOC
let [toc, fileindices] = s:ReadTOC(LatexBox_GetAuxFile(),
\ LatexBox_GetMainTexFile())
let calling_buf = bufnr('%')
" Find closest section in current buffer
let closest_index = s:FindClosestSection(toc,fileindices)
" Create TOC window and set local settings
if g:LatexBox_split_resize
silent exe "set columns+=" . g:LatexBox_split_width
endif
silent exe g:LatexBox_split_side g:LatexBox_split_width . 'vnew LaTeX\ TOC'
let b:toc = toc
let b:toc_numbers = 1
let b:calling_win = bufwinnr(calling_buf)
setlocal filetype=latextoc
" Add TOC entries and jump to the closest section
for entry in toc
call append('$', entry['number'] . "\t" . entry['text'])
endfor
if !g:LatexBox_toc_hidehelp
call append('$', "")
call append('$', "<Esc>/q: close")
call append('$', "<Space>: jump")
call append('$', "<Enter>: jump and close")
call append('$', "s: hide numbering")
endif
0delete _
execute 'normal! ' . (closest_index + 1) . 'G'
" Lock buffer
setlocal nomodifiable
endfunction
" Binary search for the closest section
" return the index of the TOC entry
function! s:FindClosestSection(toc, fileindices)
let file = expand('%:p')
if !has_key(a:fileindices, file)
return 0
endif
let imax = len(a:fileindices[file])
if imax > 0
let imin = 0
while imin < imax - 1
let i = (imax + imin) / 2
let tocindex = a:fileindices[file][i]
let entry = a:toc[tocindex]
let titlestr = entry['text']
let titlestr = escape(titlestr, '\')
let titlestr = substitute(titlestr, ' ', '\\_\\s\\+', 'g')
let [lnum, cnum] = searchpos('\\' . entry['level'] . '\_\s*{' . titlestr . '}', 'nW')
if lnum
let imax = i
else
let imin = i
endif
endwhile
return a:fileindices[file][imin]
else
return 0
endif
endfunction
let s:ConvBackPats = map([
\ ['\\''A}' , 'Á'],
\ ['\\`A}' , 'À'],
\ ['\\^A}' , 'À'],
\ ['\\¨A}' , 'Ä'],
\ ['\\"A}' , 'Ä'],
\ ['\\''a}' , 'á'],
\ ['\\`a}' , 'à'],
\ ['\\^a}' , 'à'],
\ ['\\¨a}' , 'ä'],
\ ['\\"a}' , 'ä'],
\ ['\\''E}' , 'É'],
\ ['\\`E}' , 'È'],
\ ['\\^E}' , 'Ê'],
\ ['\\¨E}' , 'Ë'],
\ ['\\"E}' , 'Ë'],
\ ['\\''e}' , 'é'],
\ ['\\`e}' , 'è'],
\ ['\\^e}' , 'ê'],
\ ['\\¨e}' , 'ë'],
\ ['\\"e}' , 'ë'],
\ ['\\''I}' , 'Í'],
\ ['\\`I}' , 'Î'],
\ ['\\^I}' , 'Ì'],
\ ['\\¨I}' , 'Ï'],
\ ['\\"I}' , 'Ï'],
\ ['\\''i}' , 'í'],
\ ['\\`i}' , 'î'],
\ ['\\^i}' , 'ì'],
\ ['\\¨i}' , 'ï'],
\ ['\\"i}' , 'ï'],
\ ['\\''{\?\\i }' , 'í'],
\ ['\\''O}' , 'Ó'],
\ ['\\`O}' , 'Ò'],
\ ['\\^O}' , 'Ô'],
\ ['\\¨O}' , 'Ö'],
\ ['\\"O}' , 'Ö'],
\ ['\\''o}' , 'ó'],
\ ['\\`o}' , 'ò'],
\ ['\\^o}' , 'ô'],
\ ['\\¨o}' , 'ö'],
\ ['\\"o}' , 'ö'],
\ ['\\''U}' , 'Ú'],
\ ['\\`U}' , 'Ù'],
\ ['\\^U}' , 'Û'],
\ ['\\¨U}' , 'Ü'],
\ ['\\"U}' , 'Ü'],
\ ['\\''u}' , 'ú'],
\ ['\\`u}' , 'ù'],
\ ['\\^u}' , 'û'],
\ ['\\¨u}' , 'ü'],
\ ['\\"u}' , 'ü'],
\ ['\\`N}' , 'Ǹ'],
\ ['\\\~N}' , 'Ñ'],
\ ['\\''n}' , 'ń'],
\ ['\\`n}' , 'ǹ'],
\ ['\\\~n}' , 'ñ'],
\], '[''\C\(\\IeC\s*{\)\?'' . v:val[0], v:val[1]]')
" }}}
" TOC Command {{{
command! LatexTOC call LatexBox_TOC()
command! LatexTOCToggle call LatexBox_TOC(1)
" }}}
" vim:fdm=marker:ff=unix:noet:ts=4:sw=4

193
ftplugin/latextoc.vim Normal file
View File

@@ -0,0 +1,193 @@
" {{{1 Settings
setlocal buftype=nofile
setlocal bufhidden=wipe
setlocal nobuflisted
setlocal noswapfile
setlocal nowrap
setlocal nospell
setlocal cursorline
setlocal nonumber
setlocal nolist
setlocal tabstop=8
setlocal cole=0
setlocal cocu=nvic
if g:LatexBox_fold_toc
setlocal foldmethod=expr
setlocal foldexpr=TOCFoldLevel(v:lnum)
setlocal foldtext=TOCFoldText()
endif
" }}}1
" {{{1 Functions
" {{{2 TOCClose
function! s:TOCClose()
if g:LatexBox_split_resize
silent exe "set columns-=" . g:LatexBox_split_width
endif
bwipeout
endfunction
" {{{2 TOCToggleNumbers
function! s:TOCToggleNumbers()
if b:toc_numbers
setlocal conceallevel=3
let b:toc_numbers = 0
else
setlocal conceallevel=0
let b:toc_numbers = 1
endif
endfunction
" {{{2 EscapeTitle
function! s:EscapeTitle(titlestr)
" Credit goes to Marcin Szamotulski for the following fix. It allows to
" match through commands added by TeX.
let titlestr = substitute(a:titlestr, '\\\w*\>\s*\%({[^}]*}\)\?', '.*', 'g')
let titlestr = escape(titlestr, '\')
let titlestr = substitute(titlestr, ' ', '\\_\\s\\+', 'g')
return titlestr
endfunction
" {{{2 TOCActivate
function! s:TOCActivate(close)
let n = getpos('.')[1] - 1
if n >= len(b:toc)
return
endif
let entry = b:toc[n]
let titlestr = s:EscapeTitle(entry['text'])
" Search for duplicates
"
let i=0
let entry_hash = entry['level'].titlestr
let duplicates = 0
while i<n
let i_entry = b:toc[n]
let i_hash = b:toc[i]['level'].s:EscapeTitle(b:toc[i]['text'])
if i_hash == entry_hash
let duplicates += 1
endif
let i += 1
endwhile
let toc_bnr = bufnr('%')
let toc_wnr = winnr()
execute b:calling_win . 'wincmd w'
let files = [entry['file']]
for line in filter(readfile(entry['file']), 'v:val =~ ''\\input{''')
call add(files, matchstr(line, '{\zs.*\ze\(\.tex\)\?}') . '.tex')
endfor
" Find section in buffer (or inputted files)
call s:TOCFindMatch('\\' . entry['level'] . '\_\s*{' . titlestr . '}',
\ duplicates, files)
if a:close
if g:LatexBox_split_resize
silent exe "set columns-=" . g:LatexBox_split_width
endif
execute 'bwipeout ' . toc_bnr
else
execute toc_wnr . 'wincmd w'
endif
endfunction
" {{{2 TOCFindMatch
function! s:TOCFindMatch(strsearch,duplicates,files)
call s:TOCOpenBuf(a:files[0])
let dups = a:duplicates
" Skip duplicates
while dups > 0
if search(a:strsearch, 'w')
let dups -= 1
else
break
endif
endwhile
if search(a:strsearch, 'w')
normal! zv
return
endif
call s:TOCFindMatch(a:strsearch,dups,a:files[1:])
endfunction
" {{{2 TOCFoldLevel
function! TOCFoldLevel(lnum)
let line = getline(a:lnum)
let match_s1 = line =~# '^\w\+\s'
let match_s2 = line =~# '^\w\+\.\w\+\s'
let match_s3 = line =~# '^\w\+\.\w\+\.\w\+\s'
if g:LatexBox_fold_toc_levels >= 3
if match_s3
return ">3"
endif
endif
if g:LatexBox_fold_toc_levels >= 2
if match_s2
return ">2"
endif
endif
if match_s1
return ">1"
endif
" Don't fold options
if line =~# '^\s*$'
return 0
endif
" Return previous fold level
return "="
endfunction
" {{{2 TOCFoldText
function! TOCFoldText()
let parts = matchlist(getline(v:foldstart), '^\(.*\)\t\(.*\)$')
return printf('%-8s%-72s', parts[1], parts[2])
endfunction
" {{{2 TOCOpenBuf
function! s:TOCOpenBuf(file)
let bnr = bufnr(a:file)
if bnr == -1
execute 'badd ' . a:file
let bnr = bufnr(a:file)
endif
execute 'buffer! ' . bnr
endfunction
" }}}1
" {{{1 Mappings
nnoremap <buffer> <silent> s :call <SID>TOCToggleNumbers()<CR>
nnoremap <buffer> <silent> q :call <SID>TOCClose()<CR>
nnoremap <buffer> <silent> <Esc> :call <SID>TOCClose()<CR>
nnoremap <buffer> <silent> <Space> :call <SID>TOCActivate(0)<CR>
nnoremap <buffer> <silent> <CR> :call <SID>TOCActivate(1)<CR>
nnoremap <buffer> <silent> <leftrelease> :call <SID>TOCActivate(0)<cr>
nnoremap <buffer> <silent> <2-leftmouse> :call <SID>TOCActivate(1)<cr>
nnoremap <buffer> <silent> G G4k
nnoremap <buffer> <silent> <Esc>OA k
nnoremap <buffer> <silent> <Esc>OB j
nnoremap <buffer> <silent> <Esc>OC l
nnoremap <buffer> <silent> <Esc>OD h
" }}}1
" vim:fdm=marker:ff=unix:et:ts=4:sw=4

View File

@@ -1,6 +1,7 @@
" Vim filetype plugin
" Language: Markdown
" Maintainer: Tim Pope <vimNOSPAM@tpope.org>
" Last Change: 2013 May 30
if exists("b:did_ftplugin")
finish

107
ftplugin/mustache.vim Normal file
View File

@@ -0,0 +1,107 @@
let s:cpo_save = &cpo
set cpo&vim
" Matchit support for Mustache & Handlebars
" extending HTML matchit groups
if exists("loaded_matchit") && exists("b:match_words")
let b:match_words = b:match_words
\ . ',{:},[:],(:),'
\ . '\%({{\)\@<=#\s*\%(if\|unless\)\s*.\{-}}}'
\ . ':'
\ . '\%({{\)\@<=\s*else\s*}}'
\ . ':'
\ . '\%({{\)\@<=/\s*\%(if\|unless\)\s*}},'
\ . '\%({{\)\@<=[#^]\s*\([-0-9a-zA-Z_?!/.]\+\).\{-}}}'
\ . ':'
\ . '\%({{\)\@<=/\s*\1\s*}}'
endif
if exists("g:mustache_abbreviations")
inoremap <buffer> {{{ {{{}}}<left><left><left>
inoremap <buffer> {{ {{}}<left><left>
inoremap <buffer> {{! {{!}}<left><left>
inoremap <buffer> {{< {{<}}<left><left>
inoremap <buffer> {{> {{>}}<left><left>
inoremap <buffer> {{# {{#}}<cr>{{/}}<up><left><left>
inoremap <buffer> {{if {{#if }}<cr>{{/if}}<up><left>
inoremap <buffer> {{ife {{#if }}<cr>{{else}}<cr>{{/if}}<up><up><left>
endif
" Section movement
" Adapted from vim-ruby - many thanks to the maintainers of that plugin
function! s:sectionmovement(pattern,flags,mode,count)
norm! m'
if a:mode ==# 'v'
norm! gv
endif
let i = 0
while i < a:count
let i = i + 1
" saving current position
let line = line('.')
let col = col('.')
let pos = search(a:pattern,'W'.a:flags)
" if there's no more matches, return to last position
if pos == 0
call cursor(line,col)
return
endif
endwhile
endfunction
nnoremap <silent> <buffer> [[ :<C-U>call <SID>sectionmovement('{{','b','n',v:count1)<CR>
nnoremap <silent> <buffer> ]] :<C-U>call <SID>sectionmovement('{{','' ,'n',v:count1)<CR>
xnoremap <silent> <buffer> [[ :<C-U>call <SID>sectionmovement('{{','b','v',v:count1)<CR>
xnoremap <silent> <buffer> ]] :<C-U>call <SID>sectionmovement('{{','' ,'v',v:count1)<CR>
" Operator pending mappings
onoremap <silent> <buffer> ie :<C-U>call <SID>wrap_inside()<CR>
onoremap <silent> <buffer> ae :<C-U>call <SID>wrap_around()<CR>
xnoremap <silent> <buffer> ie :<C-U>call <SID>wrap_inside()<CR>
xnoremap <silent> <buffer> ae :<C-U>call <SID>wrap_around()<CR>
function! s:wrap_around()
" If the cursor is at the end of the tag element, move back
" so that the end tag can be detected.
while getline('.')[col('.')-1] ==# '}'
execute 'norm h'
endwhile
" Moves to the end of the closing tag
let pos = search('}}','We')
if pos != 0
if getline('.')[col('.')] ==# '}'
" Ending tag contains 3 closing brackets '}}}',
" move to the last bracket.
execute 'norm l'
endif
" select the whole tag
execute 'norm v%'
endif
endfunction
function! s:wrap_inside()
" If the cursor is at the end of the tag element, move back
" so that the end tag can be detected.
while getline('.')[col('.')-1] ==# '}'
execute 'norm h'
endwhile
" Moves to the end of the closing tag
let pos = search('}}','W')
if pos != 0
" select only inside the tag
execute 'norm v%loho'
endif
endfunction
let &cpo = s:cpo_save
unlet s:cpo_save
" vim: nofoldenable

89
ftplugin/perl.vim Normal file
View File

@@ -0,0 +1,89 @@
" Vim filetype plugin file
" Language: Perl
" Maintainer: vim-perl <vim-perl@googlegroups.com>
" Homepage: http://github.com/vim-perl/vim-perl
" Bugs/requests: http://github.com/vim-perl/vim-perl/issues
" Last Change: {{LAST_CHANGE}}
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
" Make sure the continuation lines below do not cause problems in
" compatibility mode.
let s:save_cpo = &cpo
set cpo-=C
setlocal formatoptions-=t
setlocal formatoptions+=crqol
setlocal keywordprg=perldoc\ -f
setlocal comments=:#
setlocal commentstring=#%s
" Change the browse dialog on Win32 to show mainly Perl-related files
if has("gui_win32")
let b:browsefilter = "Perl Source Files (*.pl)\t*.pl\n" .
\ "Perl Modules (*.pm)\t*.pm\n" .
\ "Perl Documentation Files (*.pod)\t*.pod\n" .
\ "All Files (*.*)\t*.*\n"
endif
" Provided by Ned Konz <ned at bike-nomad dot com>
"---------------------------------------------
setlocal include=\\<\\(use\\\|require\\)\\>
setlocal includeexpr=substitute(substitute(substitute(v:fname,'::','/','g'),'->\*','',''),'$','.pm','')
setlocal define=[^A-Za-z_]
setlocal iskeyword+=:
" The following line changes a global variable but is necessary to make
" gf and similar commands work. Thanks to Andrew Pimlott for pointing
" out the problem. If this causes a problem for you, add an
" after/ftplugin/perl.vim file that contains
" set isfname-=:
set isfname+=:
" Set this once, globally.
if !exists("perlpath")
if executable("perl")
try
if &shellxquote != '"'
let perlpath = system('perl -e "print join(q/,/,@INC)"')
else
let perlpath = system("perl -e 'print join(q/,/,@INC)'")
endif
let perlpath = substitute(perlpath,',.$',',,','')
catch /E145:/
let perlpath = ".,,"
endtry
else
" If we can't call perl to get its path, just default to using the
" current directory and the directory of the current file.
let perlpath = ".,,"
endif
endif
" Append perlpath to the existing path value, if it is set. Since we don't
" use += to do it because of the commas in perlpath, we have to handle the
" global / local settings, too.
if &l:path == ""
if &g:path == ""
let &l:path=perlpath
else
let &l:path=&g:path.",".perlpath
endif
else
let &l:path=&l:path.",".perlpath
endif
"---------------------------------------------
" Undo the stuff we changed.
let b:undo_ftplugin = "setlocal fo< com< cms< inc< inex< def< isf< kp< path<" .
\ " | unlet! b:browsefilter"
" proper matching for matchit plugin
let b:match_skip = 's:comment\|string\|perlQQ\|perlShellCommand\|perlHereDoc\|perlSubstitution\|perlTranslation\|perlMatch\|perlFormatField'
let b:match_words = '\<if\>:\<elsif\>:\<else\>'
" Restore the saved compatibility options.
let &cpo = s:save_cpo
unlet s:save_cpo

77
ftplugin/perl6.vim Normal file
View File

@@ -0,0 +1,77 @@
" Vim filetype plugin file
" Language: Perl 6
" Maintainer: vim-perl <vim-perl@googlegroups.com>
" Homepage: http://github.com/vim-perl/vim-perl
" Bugs/requests: http://github.com/vim-perl/vim-perl/issues
" Last Change: {{LAST_CHANGE}}
" Contributors: Hinrik Örn Sigurðsson <hinrik.sig@gmail.com>
"
" Based on ftplugin/perl.vim by Dan Sharp <dwsharp at hotmail dot com>
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
" Make sure the continuation lines below do not cause problems in
" compatibility mode.
let s:save_cpo = &cpo
set cpo-=C
setlocal formatoptions-=t
setlocal formatoptions+=crqol
setlocal keywordprg=p6doc
setlocal comments=:#
setlocal commentstring=#%s
" Change the browse dialog on Win32 to show mainly Perl-related files
if has("gui_win32")
let b:browsefilter = "Perl Source Files (*.pl)\t*.pl\n" .
\ "Perl Modules (*.pm)\t*.pm\n" .
\ "Perl Documentation Files (*.pod)\t*.pod\n" .
\ "All Files (*.*)\t*.*\n"
endif
" Provided by Ned Konz <ned at bike-nomad dot com>
"---------------------------------------------
setlocal include=\\<\\(use\\\|require\\)\\>
setlocal includeexpr=substitute(substitute(v:fname,'::','/','g'),'$','.pm','')
setlocal define=[^A-Za-z_]
" The following line changes a global variable but is necessary to make
" gf and similar commands work. Thanks to Andrew Pimlott for pointing out
" the problem. If this causes a " problem for you, add an
" after/ftplugin/perl6.vim file that contains
" set isfname-=:
set isfname+=:
setlocal iskeyword=48-57,_,A-Z,a-z,:,-
" Set this once, globally.
if !exists("perlpath")
if executable("perl6")
try
if &shellxquote != '"'
let perlpath = system('perl6 -e "@*INC.join(q/,/).say"')
else
let perlpath = system("perl6 -e '@*INC.join(q/,/).say'")
endif
let perlpath = substitute(perlpath,',.$',',,','')
catch /E145:/
let perlpath = ".,,"
endtry
else
" If we can't call perl to get its path, just default to using the
" current directory and the directory of the current file.
let perlpath = ".,,"
endif
endif
let &l:path=perlpath
"---------------------------------------------
" Undo the stuff we changed.
let b:undo_ftplugin = "setlocal fo< com< cms< inc< inex< def< isk<" .
\ " | unlet! b:browsefilter"
" Restore the saved compatibility options.
let &cpo = s:save_cpo
unlet s:save_cpo

View File

@@ -1,202 +0,0 @@
" File: php.vim
" Description: PHP Integration for VIM plugin
" This file is a considerable fork of the original
" PDV written by Tobias Schlitt <toby@php.net>.
" Maintainer: Steve Francia <piv@spf13.com> <http://spf13.com>
" Version: 0.9
" Last Change: 7th January 2012
"
"
" Section: script init stuff {{{1
if exists("loaded_piv")
finish
endif
let loaded_piv = 1
"
" Function: s:InitVariable() function {{{2
" This function is used to initialise a given variable to a given value. The
" variable is only initialised if it does not exist prior
"
" Args:
" -var: the name of the var to be initialised
" -value: the value to initialise var to
"
" Returns:
" 1 if the var is set, 0 otherwise
function s:InitVariable(var, value)
if !exists(a:var)
exec 'let ' . a:var . ' = ' . "'" . a:value . "'"
return 1
endif
return 0
endfunction
" {{{ Settings
" First the global PHP configuration
let php_sql_query=1 " to highlight SQL syntax in strings
let php_htmlInStrings=1 " to highlight HTML in string
let php_noShortTags = 1 " to disable short tags
let php_folding = 1 "to enable folding for classes and functions
let PHP_autoformatcomment = 1
let php_sync_method = -1
" Section: variable init calls {{{2
call s:InitVariable("g:load_doxygen_syntax", 1)
call s:InitVariable("g:syntax_extra_php", 'doxygen')
call s:InitVariable("g:syntax_extra_inc", 'doxygen')
call s:InitVariable("g:PIVCreateDefaultMappings", 1)
call s:InitVariable("g:PIVPearStyle", 0)
call s:InitVariable("g:PIVAutoClose", 0)
" Auto expand tabs to spaces
setlocal expandtab
setlocal autoindent " Auto indent after a {
setlocal smartindent
" Linewidth to 79, because of the formatoptions this is only valid for
" comments
setlocal textwidth=79
setlocal nowrap " Do not wrap lines automatically
" Correct indentation after opening a phpdocblock and automatic * on every
" line
setlocal formatoptions=qroct
" Use php syntax check when doing :make
setlocal makeprg=php\ -l\ %
" Use errorformat for parsing PHP error output
setlocal errorformat=%m\ in\ %f\ on\ line\ %l
" Switch syntax highlighting on, if it was not
if !exists("g:syntax_on") | syntax on | endif
"setlocal keywordprg=pman " Use pman for manual pages
" }}} Settings
" {{{ Command mappings
nnoremap <silent> <plug>PIVphpDocSingle :call PhpDocSingle()<CR>
vnoremap <silent> <plug>PIVphpDocRange :call PhpDocRange()<CR>
vnoremap <silent> <plug>PIVphpAlign :call PhpAlign()<CR>
"inoremap <buffer> <leader>d :call PhpDocSingle()<CR>i
" Map ; to "add ; to the end of the line, when missing"
"noremap <buffer> ; :s/\([^;]\)$/\1;/<cr>
" Map <ctrl>+p to single line mode documentation (in insert and command mode)
"inoremap <buffer> <leader>d :call PhpDocSingle()<CR>i
"nnoremap <buffer> <leader>d :call PhpDocSingle()<CR>
" Map <ctrl>+p to multi line mode documentation (in visual mode)
"vnoremap <buffer> <leader>d :call PhpDocRange()<CR>
" Map <CTRL>-H to search phpm for the function name currently under the cursor (insert mode only)
inoremap <buffer> <C-H> <ESC>:!phpm <C-R>=expand("<cword>")<CR><CR>
" }}}
" {{{ Automatic close char mapping
if g:PIVAutoClose
if g:PIVPearStyle
inoremap <buffer> { {<CR>}<C-O>O
inoremap <buffer> ( ( )<LEFT><LEFT>
else
inoremap { {<CR>}<C-O>O
inoremap ( ()<LEFT>
endif
inoremap <buffer> [ []<LEFT>
inoremap <buffer> " ""<LEFT>
inoremap <buffer> ' ''<LEFT>
endif
" }}} Automatic close char mapping
" {{{ Wrap visual selections with chars
vnoremap <buffer> ( "zdi(<C-R>z)<ESC>
vnoremap <buffer> { "zdi{<C-R>z}<ESC>
vnoremap <buffer> [ "zdi[<C-R>z]<ESC>
vnoremap <buffer> ' "zdi'<C-R>z'<ESC>
" Removed in favor of register addressing
" :vnoremap " "zdi"<C-R>z"<ESC>
" }}} Wrap visual selections with chars
" {{{ Dictionary completion
setlocal dictionary-=$VIMRUNTIME/bundle/PIV/misc/funclist.txt dictionary+=$VIMRUNTIME/bundle/PIV/misc/funclist.txt
" Use the dictionary completion
setlocal complete-=k complete+=k
" }}} Dictionary completion
" {{{ Alignment
func! PhpAlign() range
let l:paste = &g:paste
let &g:paste = 0
let l:line = a:firstline
let l:endline = a:lastline
let l:maxlength = 0
while l:line <= l:endline
" Skip comment lines
if getline (l:line) =~ '^\s*\/\/.*$'
let l:line = l:line + 1
continue
endif
" \{-\} matches ungreed *
let l:index = substitute (getline (l:line), '^\s*\(.\{-\}\)\s*\S\{0,1}=\S\{0,1\}\s.*$', '\1', "")
let l:indexlength = strlen (l:index)
let l:maxlength = l:indexlength > l:maxlength ? l:indexlength : l:maxlength
let l:line = l:line + 1
endwhile
let l:line = a:firstline
let l:format = "%s%-" . l:maxlength . "s %s %s"
while l:line <= l:endline
if getline (l:line) =~ '^\s*\/\/.*$'
let l:line = l:line + 1
continue
endif
let l:linestart = substitute (getline (l:line), '^\(\s*\).*', '\1', "")
let l:linekey = substitute (getline (l:line), '^\s*\(.\{-\}\)\s*\(\S\{0,1}=\S\{0,1\}\)\s\(.*\)$', '\1', "")
let l:linesep = substitute (getline (l:line), '^\s*\(.\{-\}\)\s*\(\S\{0,1}=\S\{0,1\}\)\s\(.*\)$', '\2', "")
let l:linevalue = substitute (getline (l:line), '^\s*\(.\{-\}\)\s*\(\S\{0,1}=\S\{0,1\}\)\s\(.*\)$', '\3', "")
let l:newline = printf (l:format, l:linestart, l:linekey, l:linesep, l:linevalue)
call setline (l:line, l:newline)
let l:line = l:line + 1
endwhile
let &g:paste = l:paste
endfunc
" }}}
function! s:CreateNMap(target, combo)
if !hasmapto(a:target, 'n')
exec 'nmap ' . a:combo . ' ' . a:target
endif
endfunction
function! s:CreateVMap(target, combo)
if !hasmapto(a:target, 'v')
exec 'vmap ' . a:combo . ' ' . a:target
endif
endfunction
function! s:CreateMaps(target, combo)
call s:CreateNMap(a:target,a:combo)
call s:CreateVMap(a:target,a:combo)
endfunction
if g:PIVCreateDefaultMappings
call s:CreateNMap('<plug>PIVphpDocSingle', ',pd')
call s:CreateVMap('<plug>PIVphpDocRange', ',pd')
call s:CreateMaps('<plug>PIVphpAlign ', ',pa')
endif

View File

@@ -1,547 +0,0 @@
" PDV (phpDocumentor for Vim)
" ===========================
"
" Version: 1.1.3
"
" Copyright 2005 by Tobias Schlitt <toby@php.net>
" Inspired by phpDoc script for Vim by Vidyut Luther (http://www.phpcult.com/).
"
" modified by kevin olson (acidjazz@gmail.com) - 03/19/2009
" - added folding support
"
" Provided under the GPL (http://www.gnu.org/copyleft/gpl.html).
"
" This script provides functions to generate phpDocumentor conform
" documentation blocks for your PHP code. The script currently
" documents:
"
" - Classes
" - Methods/Functions
" - Attributes
"
" All of those supporting all PHP 4 and 5 syntax elements.
"
" Beside that it allows you to define default values for phpDocumentor tags
" like @version (I use $id$ here), @author, @license and so on.
"
" For function/method parameters and attributes, the script tries to guess the
" type as good as possible from PHP5 type hints or default values (array, bool,
" int, string...).
"
" You can use this script by mapping the function PhpDoc() to any
" key combination. Hit this on the line where the element to document
" resides and the doc block will be created directly above that line.
"
" Installation
" ============
"
" For example include into your .vimrc:
"
" source ~/.vim/php-doc.vim
" imap <C-o> :set paste<CR>:call PhpDoc()<CR>:set nopaste<CR>i
"
" This includes the script and maps the combination <ctrl>+o (only in
" insert mode) to the doc function.
"
" Changelog
" =========
"
" Version 1.0.0
" -------------
"
" * Created the initial version of this script while playing around with VIM
" scripting the first time and trying to fix Vidyut's solution, which
" resulted in a complete rewrite.
"
" Version 1.0.1
" -------------
" * Fixed issues when using tabs instead of spaces.
" * Fixed some parsing bugs when using a different coding style.
" * Fixed bug with call-by-reference parameters.
" * ATTENTION: This version already has code for the next version 1.1.0,
" which is propably not working!
"
" Version 1.1.0 (preview)
" -------------
" * Added foldmarker generation.
"
" Version 1.1.2
" -------------
" * Completed foldmarker commenting for functions
"
if has ("user_commands")
" {{{ Globals
" After phpDoc standard
let g:pdv_cfg_CommentHead = "/**"
let g:pdv_cfg_Comment1 = " * "
let g:pdv_cfg_Commentn = " * "
let g:pdv_cfg_CommentTail = " */"
let g:pdv_cfg_CommentEnd = "/* }}} */"
let g:pdv_cfg_CommentSingle = "//"
" Default values
let g:pdv_cfg_Type = "mixed"
" let g:pdv_cfg_Package = "Framework"
let g:pdv_cfg_Package = "Webdav"
let g:pdv_cfg_Version = "//autogen//"
let g:pdv_cfg_Author = ""
let g:pdv_cfg_Copyright = "Copyright (c) 2010 All rights reserved."
let g:pdv_cfg_License = "PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}"
let g:pdv_cfg_ReturnVal = "void"
" Whether to create @uses tags for implementation of interfaces and inheritance
let g:pdv_cfg_Uses = 1
" Options
" :set paste before documenting (1|0)? Recommended.
let g:pdv_cfg_paste = 1
" Whether for PHP5 code PHP4 tags should be set, like @access,... (1|0)?
let g:pdv_cfg_php4always = 1
" Whether to guess scopes after PEAR coding standards:
" $_foo/_bar() == <private|protected> (1|0)?
let g:pdv_cfg_php4guess = 1
" If you selected 1 for the last value, this scope identifier will be used for
" the identifiers having an _ in the first place.
let g:pdv_cfg_php4guessval = "protected"
"
" Regular expressions
"
let g:pdv_re_comment = ' *\*/ *'
" (private|protected|public)
let g:pdv_re_scope = '\(private\|protected\|public\)'
" (static)
let g:pdv_re_static = '\(static\)'
" (abstract)
let g:pdv_re_abstract = '\(abstract\)'
" (final)
let g:pdv_re_final = '\(final\)'
" [:space:]*(private|protected|public|static|abstract)*[:space:]+[:identifier:]+\([:params:]\)
let g:pdv_re_func = '^\s*\([a-zA-Z ]*\)function\s\+\([^ (]\+\)\s*(\s*\(.*\)\s*)\s*[{;]\?$'
let g:pdv_re_funcend = '^\s*}$'
" [:typehint:]*[:space:]*$[:identifier]\([:space:]*=[:space:]*[:value:]\)?
let g:pdv_re_param = ' *\([^ &]*\) *&\?\$\([A-Za-z_][A-Za-z0-9_]*\) *=\? *\(.*\)\?$'
" [:space:]*(private|protected|public\)[:space:]*$[:identifier:]+\([:space:]*=[:space:]*[:value:]+\)*;
let g:pdv_re_attribute = '^\s*\(\(private\|public\|protected\|var\|static\)\+\)\s*\$\([^ ;=]\+\)[ =]*\(.*\);\?$'
" [:spacce:]*(abstract|final|)[:space:]*(class|interface)+[:space:]+\(extends ([:identifier:])\)?[:space:]*\(implements ([:identifier:][, ]*)+\)?
let g:pdv_re_class = '^\s*\([a-zA-Z]*\)\s*\(interface\|class\)\s*\([^ ]\+\)\s*\(extends\)\?\s*\([a-zA-Z0-9]*\)\?\s*\(implements*\)\? *\([a-zA-Z0-9_ ,]*\)\?.*$'
let g:pdv_re_array = "^array *(.*"
let g:pdv_re_float = '^[0-9.]\+'
let g:pdv_re_int = '^[0-9]\+$'
let g:pdv_re_string = "['\"].*"
let g:pdv_re_bool = "[true false]"
let g:pdv_re_indent = '^\s*'
" Shortcuts for editing the text:
let g:pdv_cfg_BOL = "norm! o"
let g:pdv_cfg_EOL = ""
" }}}
" {{{ PhpDocSingle()
" Document a single line of code ( does not check if doc block already exists )
func! PhpDocSingle()
let l:endline = line(".") + 1
call PhpDoc()
exe "norm! " . l:endline . "G$"
endfunc
" }}}
" {{{ PhpDocRange()
" Documents a whole range of code lines ( does not add defualt doc block to
" unknown types of lines ). Skips elements where a docblock is already
" present.
func! PhpDocRange() range
let l:line = a:firstline
let l:endLine = a:lastline
let l:elementName = ""
while l:line <= l:endLine
" TODO: Replace regex check for existing doc with check more lines
" above...
if (getline(l:line) =~ g:pdv_re_func || getline(l:line) =~ g:pdv_re_attribute || getline(l:line) =~ g:pdv_re_class) && getline(l:line - 1) !~ g:pdv_re_comment
let l:docLines = 0
" Ensure we are on the correct line to run PhpDoc()
exe "norm! " . l:line . "G$"
" No matter what, this returns the element name
let l:elementName = PhpDoc()
let l:endLine = l:endLine + (line(".") - l:line) + 1
let l:line = line(".") + 1
endif
let l:line = l:line + 1
endwhile
endfunc
" }}}
" {{{ PhpDocFold()
" func! PhpDocFold(name)
" let l:startline = line(".")
" let l:currentLine = l:startLine
" let l:commentHead = escape(g:pdv_cfg_CommentHead, "*.");
" let l:txtBOL = g:pdv_cfg_BOL . matchstr(l:name, '^\s*')
" " Search above for comment start
" while (l:currentLine > 1)
" if (matchstr(l:commentHead, getline(l:currentLine)))
" break;
" endif
" let l:currentLine = l:currentLine + 1
" endwhile
" " Goto 1 line above and open a newline
" exe "norm! " . (l:currentLine - 1) . "Go\<ESC>"
" " Write the fold comment
" exe l:txtBOL . g:pdv_cfg_CommentSingle . " {"."{{ " . a:name . g:pdv_cfg_EOL
" " Add another newline below that
" exe "norm! o\<ESC>"
" " Search for our comment line
" let l:currentLine = line(".")
" while (l:currentLine <= line("$"))
" " HERE!!!!
" endwhile
"
"
" endfunc
" }}}
" {{{ PhpDoc()
func! PhpDoc()
" Needed for my .vimrc: Switch off all other enhancements while generating docs
let l:paste = &g:paste
let &g:paste = g:pdv_cfg_paste == 1 ? 1 : &g:paste
let l:line = getline(".")
let l:result = ""
if l:line =~ g:pdv_re_func
let l:result = PhpDocFunc()
elseif l:line =~ g:pdv_re_funcend
let l:result = PhpDocFuncEnd()
elseif l:line =~ g:pdv_re_attribute
let l:result = PhpDocVar()
elseif l:line =~ g:pdv_re_class
let l:result = PhpDocClass()
else
let l:result = PhpDocDefault()
endif
" if g:pdv_cfg_folds == 1
" PhpDocFolds(l:result)
" endif
let &g:paste = l:paste
return l:result
endfunc
" }}}
" {{{ PhpDocFuncEnd()
func! PhpDocFuncEnd()
call append(line('.'), matchstr(getline('.'), '^\s*') . g:pdv_cfg_CommentEnd)
endfunc
" }}}
" {{{ PhpDocFuncEndAuto()
func! PhpDocFuncEndAuto()
call search('{')
call searchpair('{', '', '}')
call append(line('.'), matchstr(getline('.'), '^\s*') . g:pdv_cfg_CommentEnd)
endfunc
" }}}
" {{{ PhpDocFunc()
func! PhpDocFunc()
" Line for the comment to begin
let commentline = line (".") - 1
let l:name = substitute (getline ("."), '^\(.*\)\/\/.*$', '\1', "")
"exe g:pdv_cfg_BOL . "DEBUG:" . name. g:pdv_cfg_EOL
" First some things to make it more easy for us:
" tab -> space && space+ -> space
" let l:name = substitute (l:name, '\t', ' ', "")
" Orphan. We're now using \s everywhere...
" Now we have to split DECL in three parts:
" \[(skopemodifier\)]\(funcname\)\(parameters\)
let l:indent = matchstr(l:name, g:pdv_re_indent)
let l:modifier = substitute (l:name, g:pdv_re_func, '\1', "g")
let l:funcname = substitute (l:name, g:pdv_re_func, '\2', "g")
let l:parameters = substitute (l:name, g:pdv_re_func, '\3', "g") . ","
let l:params = substitute (l:name, g:pdv_re_func, '\3', "g")
let l:sparams = substitute (l:params, '[$ ]', '', "g")
let l:scope = PhpDocScope(l:modifier, l:funcname)
let l:static = g:pdv_cfg_php4always == 1 ? matchstr(l:modifier, g:pdv_re_static) : ""
let l:abstract = g:pdv_cfg_php4always == 1 ? matchstr(l:modifier, g:pdv_re_abstract) : ""
let l:final = g:pdv_cfg_php4always == 1 ? matchstr(l:modifier, g:pdv_re_final) : ""
exe "norm! " . commentline . "G$"
" Local indent
let l:txtBOL = g:pdv_cfg_BOL . l:indent
exec l:txtBOL . "/* " . l:scope ." ". funcname . "(" . l:params . ") {{" . "{ */ " . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_CommentHead . g:pdv_cfg_EOL
" added folding
exe l:txtBOL . g:pdv_cfg_Comment1 . funcname . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Commentn . g:pdv_cfg_EOL
while (l:parameters != ",") && (l:parameters != "")
" Save 1st parameter
let _p = substitute (l:parameters, '\([^,]*\) *, *\(.*\)', '\1', "")
" Remove this one from list
let l:parameters = substitute (l:parameters, '\([^,]*\) *, *\(.*\)', '\2', "")
" PHP5 type hint?
let l:paramtype = substitute (_p, g:pdv_re_param, '\1', "")
" Parameter name
let l:paramname = substitute (_p, g:pdv_re_param, '\2', "")
" Parameter default
let l:paramdefault = substitute (_p, g:pdv_re_param, '\3', "")
if l:paramtype == ""
let l:paramtype = PhpDocType(l:paramdefault)
endif
if l:paramtype != ""
let l:paramtype = " " . l:paramtype
endif
exe l:txtBOL . g:pdv_cfg_Commentn . "@param" . l:paramtype . " $" . l:paramname . " " . g:pdv_cfg_EOL
endwhile
if l:static != ""
exe l:txtBOL . g:pdv_cfg_Commentn . "@static" . g:pdv_cfg_EOL
endif
if l:abstract != ""
exe l:txtBOL . g:pdv_cfg_Commentn . "@abstract" . g:pdv_cfg_EOL
endif
if l:final != ""
exe l:txtBOL . g:pdv_cfg_Commentn . "@final" . g:pdv_cfg_EOL
endif
if l:scope != ""
exe l:txtBOL . g:pdv_cfg_Commentn . "@access " . l:scope . g:pdv_cfg_EOL
endif
exe l:txtBOL . g:pdv_cfg_Commentn . "@return " . g:pdv_cfg_ReturnVal . g:pdv_cfg_EOL
" Close the comment block.
exe l:txtBOL . g:pdv_cfg_CommentTail . g:pdv_cfg_EOL
return l:modifier ." ". l:funcname . PhpDocFuncEndAuto()
endfunc
" }}}
" {{{ PhpDocVar()
func! PhpDocVar()
" Line for the comment to begin
let commentline = line (".") - 1
let l:name = substitute (getline ("."), '^\(.*\)\/\/.*$', '\1', "")
" Now we have to split DECL in three parts:
" \[(skopemodifier\)]\(funcname\)\(parameters\)
" let l:name = substitute (l:name, '\t', ' ', "")
" Orphan. We're now using \s everywhere...
let l:indent = matchstr(l:name, g:pdv_re_indent)
let l:modifier = substitute (l:name, g:pdv_re_attribute, '\1', "g")
let l:varname = substitute (l:name, g:pdv_re_attribute, '\3', "g")
let l:default = substitute (l:name, g:pdv_re_attribute, '\4', "g")
let l:scope = PhpDocScope(l:modifier, l:varname)
let l:static = g:pdv_cfg_php4always == 1 ? matchstr(l:modifier, g:pdv_re_static) : ""
let l:type = PhpDocType(l:default)
exe "norm! " . commentline . "G$"
" Local indent
let l:txtBOL = g:pdv_cfg_BOL . l:indent
exe l:txtBOL . g:pdv_cfg_CommentHead . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Comment1 . l:varname . " " . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Commentn . g:pdv_cfg_EOL
if l:static != ""
exe l:txtBOL . g:pdv_cfg_Commentn . "@static" . g:pdv_cfg_EOL
endif
exe l:txtBOL . g:pdv_cfg_Commentn . "@var " . l:type . g:pdv_cfg_EOL
if l:scope != ""
exe l:txtBOL . g:pdv_cfg_Commentn . "@access " . l:scope . g:pdv_cfg_EOL
endif
" Close the comment block.
exe l:txtBOL . g:pdv_cfg_CommentTail . g:pdv_cfg_EOL
return l:modifier ." ". l:varname
endfunc
" }}}
" {{{ PhpDocClass()
func! PhpDocClass()
" Line for the comment to begin
let commentline = line (".") - 1
let l:name = substitute (getline ("."), '^\(.*\)\/\/.*$', '\1', "")
"exe g:pdv_cfg_BOL . "DEBUG:" . name. g:pdv_cfg_EOL
" First some things to make it more easy for us:
" tab -> space && space+ -> space
" let l:name = substitute (l:name, '\t', ' ', "")
" Orphan. We're now using \s everywhere...
" Now we have to split DECL in three parts:
" \[(skopemodifier\)]\(classname\)\(parameters\)
let l:indent = matchstr(l:name, g:pdv_re_indent)
let l:modifier = substitute (l:name, g:pdv_re_class, '\1', "g")
let l:classname = substitute (l:name, g:pdv_re_class, '\3', "g")
let l:extends = g:pdv_cfg_Uses == 1 ? substitute (l:name, g:pdv_re_class, '\5', "g") : ""
let l:interfaces = g:pdv_cfg_Uses == 1 ? substitute (l:name, g:pdv_re_class, '\7', "g") . "," : ""
let l:abstract = g:pdv_cfg_php4always == 1 ? matchstr(l:modifier, g:pdv_re_abstract) : ""
let l:final = g:pdv_cfg_php4always == 1 ? matchstr(l:modifier, g:pdv_re_final) : ""
exe "norm! " . commentline . "G$"
" Local indent
let l:txtBOL = g:pdv_cfg_BOL . l:indent
exe l:txtBOL . g:pdv_cfg_CommentHead . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Comment1 . l:classname . " " . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Commentn . g:pdv_cfg_EOL
if l:extends != "" && l:extends != "implements"
exe l:txtBOL . g:pdv_cfg_Commentn . "@uses " . l:extends . g:pdv_cfg_EOL
endif
while (l:interfaces != ",") && (l:interfaces != "")
" Save 1st parameter
let interface = substitute (l:interfaces, '\([^, ]*\) *, *\(.*\)', '\1', "")
" Remove this one from list
let l:interfaces = substitute (l:interfaces, '\([^, ]*\) *, *\(.*\)', '\2', "")
exe l:txtBOL . g:pdv_cfg_Commentn . "@uses " . l:interface . g:pdv_cfg_EOL
endwhile
if l:abstract != ""
exe l:txtBOL . g:pdv_cfg_Commentn . "@abstract" . g:pdv_cfg_EOL
endif
if l:final != ""
exe l:txtBOL . g:pdv_cfg_Commentn . "@final" . g:pdv_cfg_EOL
endif
exe l:txtBOL . g:pdv_cfg_Commentn . "@package " . g:pdv_cfg_Package . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Commentn . "@version " . g:pdv_cfg_Version . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Commentn . "@copyright " . g:pdv_cfg_Copyright . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Commentn . "@author " . g:pdv_cfg_Author g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Commentn . "@license " . g:pdv_cfg_License . g:pdv_cfg_EOL
" Close the comment block.
exe l:txtBOL . g:pdv_cfg_CommentTail . g:pdv_cfg_EOL
return l:modifier ." ". l:classname
endfunc
" }}}
" {{{ PhpDocScope()
func! PhpDocScope(modifiers, identifier)
" exe g:pdv_cfg_BOL . DEBUG: . a:modifiers . g:pdv_cfg_EOL
let l:scope = ""
if matchstr (a:modifiers, g:pdv_re_scope) != ""
if g:pdv_cfg_php4always == 1
let l:scope = matchstr (a:modifiers, g:pdv_re_scope)
else
let l:scope = "x"
endif
endif
if l:scope =~ "^\s*$" && g:pdv_cfg_php4guess
if a:identifier[0] == "_"
let l:scope = g:pdv_cfg_php4guessval
else
let l:scope = "public"
endif
endif
return l:scope != "x" ? l:scope : ""
endfunc
" }}}
" {{{ PhpDocType()
func! PhpDocType(typeString)
let l:type = ""
if a:typeString =~ g:pdv_re_array
let l:type = "array"
endif
if a:typeString =~ g:pdv_re_float
let l:type = "float"
endif
if a:typeString =~ g:pdv_re_int
let l:type = "int"
endif
if a:typeString =~ g:pdv_re_string
let l:type = "string"
endif
if a:typeString =~ g:pdv_re_bool
let l:type = "bool"
endif
if l:type == ""
let l:type = g:pdv_cfg_Type
endif
return l:type
endfunc
" }}}
" {{{ PhpDocDefault()
func! PhpDocDefault()
" Line for the comment to begin
let commentline = line (".") - 1
let l:indent = matchstr(getline("."), '^\ *')
exe "norm! " . commentline . "G$"
" Local indent
let l:txtBOL = g:pdv_cfg_BOL . indent
exe l:txtBOL . g:pdv_cfg_CommentHead . g:pdv_cfg_EOL
exe l:txtBOL . g:pdv_cfg_Commentn . " " . g:pdv_cfg_EOL
" Close the comment block.
exe l:txtBOL . g:pdv_cfg_CommentTail . g:pdv_cfg_EOL
endfunc
" }}}
endif " user_commands

69
ftplugin/r.vim Normal file
View File

@@ -0,0 +1,69 @@
" ftplugin for R files
"
" Author: Iago Mosqueira <i.mosqueira@ic.ac.uk>
" Author: Johannes Ranke <jranke@uni-bremen.de>
" Author: Fernando Henrique Ferraz Pereira da Rosa <feferraz@ime.usp.br>
" Maintainer: Johannes Ranke <jranke@uni-bremen.de>
" Last Change: 2007 Nov 21
" SVN: $Id: r.vim 75 2007-11-21 13:34:02Z ranke $
"
" Code written in vim is sent to R through a perl pipe
" [funnel.pl, by Larry Clapp <vim@theclapp.org>], as individual lines,
" blocks, or the whole file.
" Press <F2> to open a new xterm with a new R interpreter listening
" to its standard input (you can type R commands into the xterm)
" as well as to code pasted from within vim.
"
" After selecting a visual block, 'r' sends it to the R interpreter
"
" In insert mode, <M-Enter> sends the active line to R and moves to the next
" line (write and process mode).
"
" Maps:
" <F2> Start a listening R interpreter in new xterm
" <F3> Start a listening R-devel interpreter in new xterm
" <F4> Start a listening R --vanilla interpreter in new xterm
" <F5> Run current file
" <F9> Run line under cursor
" r Run visual block
" <M-Enter> Write and process
" Only do this when not yet done for this buffer
if exists("b:did_ftplugin")
finish
endif
" Don't load another plugin for this buffer
let b:did_ftplugin = 1
" Disable backup for .r-pipe
setl backupskip=.*pipe
" Set tabstop so it is compatible with the emacs edited code. Personally, I
" prefer shiftwidth=2, which I have in my .vimrc anyway
set expandtab
set shiftwidth=4
set tabstop=8
" Start a listening R interpreter in new xterm
noremap <buffer> <F2> :!xterm -T 'R' -e funnel.pl ~/.r-pipe "R && echo -e 'Interpreter has finished. Exiting. Goodbye.\n'"&<CR><CR>
" Start a listening R-devel interpreter in new xterm
noremap <buffer> <F3> :!xterm -T 'R' -e funnel.pl ~/.r-pipe "R-devel && echo 'Interpreter has finished. Exiting. Goodbye.'"&<CR><CR>
" Start a listening R --vanilla interpreter in new xterm
noremap <buffer> <F4> :!xterm -T 'R' -e funnel.pl ~/.r-pipe "R -vanilla && echo 'Interpreter has finished. Exiting. Goodbye.'"&<CR><CR>
" Send line under cursor to R
noremap <buffer> <F9> :execute line(".") 'w >> ~/.r-pipe'<CR>
inoremap <buffer> <F9> <Esc> :execute line(".") 'w >> ~/.r-pipe'<CR>
" Send visual selected block to R
vnoremap <buffer> r :w >> ~/.r-pipe<CR>
" Write and process mode (somehow mapping <C-Enter> does not work)
inoremap <M-Enter> <Esc>:execute line(".") 'w >> ~/.r-pipe'<CR>o
" Send current file to R
noremap <buffer> <F5> :execute '1 ,' line("$") 'w >> ~/.r-pipe' <CR><CR>

48
ftplugin/rhelp.vim Normal file
View File

@@ -0,0 +1,48 @@
" ftplugin for R help files
"
" Author: Johannes Ranke <jranke@uni-bremen.de>
" Last Change: 2007 Nov 21
" SVN: $Id: rhelp.vim 75 2007-11-21 13:34:02Z ranke $
"
" Usage:
"
" Press <F2> to open a new xterm with a new R interpreter listening
" to its standard input (you can type R commands into the xterm)
" as well as to code pasted from within vim.
"
" After selecting a visual block, 'r' sends it to the R interpreter
"
" Add to filetypes.vim, if you don't use vim 7
" au BufNewFile,BufRead *.Rd,*.rd setf rhelp
"
" Maps:
" <F2> Start a listening R interpreter in new xterm
" <F9> Run line under cursor
" r Run visual block
" <M-Enter> Write and process R code
" Only do this when not yet done for this buffer
if exists("b:did_ftplugin")
finish
endif
" Don't load another plugin for this buffer
let b:did_ftplugin = 1
" Set tabbing
set expandtab
set tabstop=2
set shiftwidth=2
" Start a listening R interpreter in new xterm
noremap <buffer> <F2> :!xterm -T 'R' -e funnel.pl ~/.r-pipe "R && echo -e 'Interpreter has finished. Exiting. Goodbye.\n'"&<CR><CR>
" Send line under cursor to R
noremap <buffer> <F9> :execute line(".") 'w >> ~/.r-pipe'<CR>
inoremap <buffer> <F9> <Esc> :execute line(".") 'w >> ~/.r-pipe'<CR>
" Send visual selected block to R
vnoremap <buffer> r :w >> ~/.r-pipe<CR>
" Write and process mode (somehow mapping <C-Enter> does not work)
inoremap <M-Enter> <Esc>:execute line(".") 'w >> ~/.r-pipe'<CR>o

59
ftplugin/rnoweb.vim Normal file
View File

@@ -0,0 +1,59 @@
" ftplugin for Sweave files containing both LaTeX and R code
"
" Maintainer: Johannes Ranke <jranke@uni-bremen.de>
" Last Change: 2007 Nov 21
" SVN: $Id: rnoweb.vim 75 2007-11-21 13:34:02Z ranke $
"
" Usage:
"
" Press <F2> to open a new xterm with a new R interpreter listening
" to its standard input (you can type R commands into the xterm)
" as well as to code pasted from within vim.
"
" A Makefile for producing R noweb files is in included in my Vim script
" R.vim:
" http://www.vim.org/scripts/script.php?script_id=1048
" You can also look in my SVN repository under:
" http://kri/viewcvs/*checkout*/Makefile.rnoweb?root=vim
"
"
" After selecting a visual block, 'r' sends it to the R interpreter
"
" Add to filetypes.vim, if you don't use vim 7
" au BufNewFile,BufRead *.Rnw,*.rnw setf rnoweb
" and/or
" au BufNewFile,BufRead *.Snw,*.snw setf rnoweb
"
" Maps:
" <F2> Start a listening R interpreter in new xterm
" <F9> Run line under cursor
" r Run visual block
" <M-Enter> Write and process R code
" Only do this when not yet done for this buffer
if exists("b:did_ftplugin")
finish
endif
" Don't load another plugin for this buffer
let b:did_ftplugin = 1
" Disable backup for .r-pipe
setl backupskip=.*pipe
" Set R friendly tabbing
set expandtab
set shiftwidth=2
" Start a listening R interpreter in new xterm
noremap <buffer> <F2> :!xterm -T 'R' -e funnel.pl ~/.r-pipe "R && echo -e 'Interpreter has finished. Exiting. Goodbye.\n'"&<CR><CR>
" Send line under cursor to R
noremap <buffer> <F9> :execute line(".") 'w >> ~/.r-pipe'<CR>
inoremap <buffer> <F9> <Esc> :execute line(".") 'w >> ~/.r-pipe'<CR>
" Send visual selected block to R
vnoremap <buffer> r :w >> ~/.r-pipe<CR>
" Write and process mode (somehow mapping <C-Enter> does not work)
inoremap <M-Enter> <Esc>:execute line(".") 'w >> ~/.r-pipe'<CR>o

45
ftplugin/rust.vim Normal file
View File

@@ -0,0 +1,45 @@
" Vim syntax file
" Language: Rust
" Maintainer: Chris Morgan <me@chrismorgan.info>
" Last Change: 2013 Jul 10
if exists("b:did_ftplugin")
finish
endif
let b:did_ftplugin = 1
" 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.
" This does not affect indentation at all (I tested it with and without
" leader), merely whether a leader is inserted by default or not.
if exists("g:rust_bang_comment_leader") && g:rust_bang_comment_leader == 1
" 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
" leaders. I'm fairly sure that's a Vim bug.
setlocal comments=s1:/*,mb:*,ex:*/,s0:/*,mb:\ ,ex:*/,:///,://!,://
else
setlocal comments=s0:/*!,m:\ ,ex:*/,s1:/*,mb:*,ex:*/,:///,://!,://
endif
setlocal commentstring=//%s
setlocal formatoptions-=t formatoptions+=croqnl
" j was only added in 7.3.541, so stop complaints about its nonexistence
silent! setlocal formatoptions+=j
" This includeexpr isn't perfect, but it's a good start
setlocal includeexpr=substitute(v:fname,'::','/','g')
" NOT adding .rc as it's being phased out (0.7)
setlocal suffixesadd=.rs
if exists("g:ftplugin_rust_source_path")
let &l:path=g:ftplugin_rust_source_path . ',' . &l:path
endif
if exists("g:loaded_delimitMate")
if exists("b:delimitMate_excluded_regions")
let b:rust_original_delimitMate_excluded_regions = b:delimitMate_excluded_regions
endif
let b:delimitMate_excluded_regions = delimitMate#Get("excluded_regions") . ',rustLifetimeCandidate,rustGenericLifetimeCandidate'
endif
let b:undo_ftplugin = "setlocal formatoptions< comments< commentstring< includeexpr< suffixesadd< | if exists('b:rust_original_delimitMate_excluded_regions') | let b:delimitMate_excluded_regions = b:rust_original_delimitMate_excluded_regions | unlet b:rust_original_delimitMate_excluded_regions | elseif exists('b:delimitMate_excluded_regions') | unlet b:delimitMate_excluded_regions | endif"

View File

@@ -1,9 +1,8 @@
setlocal textwidth=140
setlocal shiftwidth=2
setlocal softtabstop=2
setlocal expandtab
setlocal formatoptions=tcqr
setlocal commentstring=//%s
let &l:include = '^\s*import'
let &l:includeexpr = 'substitute(v:fname,"\\.","/","g")'
setlocal path+=src/main/scala,src/test/scala
setlocal suffixesadd=.scala
set makeprg=sbt\ -Dsbt.log.noformat=true\ compile
set efm=%E\ %#[error]\ %f:%l:\ %m,%C\ %#[error]\ %p^,%-C%.%#,%Z,
@@ -117,16 +116,21 @@ if globpath(&rtp, 'plugin/fuf.vim') != ''
return scala#GetDirForFuzzyFinder(a:from, 'src/../')
endfunction
nnoremap <buffer> <silent> ,ft :FufFile <c-r>=scala#GetTestDirForFuzzyFinder('%:p:h')<cr><cr>
nnoremap <buffer> <silent> ,fs :FufFile <c-r>=scala#GetMainDirForFuzzyFinder('%:p:h')<cr><cr>
nnoremap <buffer> <silent> ,fr :FufFile <c-r>=scala#GetRootDirForFuzzyFinder('%:p:h')<cr><cr>
" If you want to disable the default key mappings, write the following line in
" your ~/.vimrc
" let g:scala_use_default_keymappings = 0
if get(g:, 'scala_use_default_keymappings', 1)
nnoremap <buffer> <silent> <Leader>ft :FufFile <c-r>=scala#GetTestDirForFuzzyFinder('%:p:h')<cr><cr>
nnoremap <buffer> <silent> <Leader>fs :FufFile <c-r>=scala#GetMainDirForFuzzyFinder('%:p:h')<cr><cr>
nnoremap <buffer> <silent> <Leader>fr :FufFile <c-r>=scala#GetRootDirForFuzzyFinder('%:p:h')<cr><cr>
endif
endif
" If you want to disable the default key mappings, write the following line in
" your ~/.vimrc
" let g:scala_use_default_keymappings = 0
if get(g:, 'scala_use_default_keymappings', 1)
nnoremap <buffer> ,jt :call JustifyCurrentLine()<cr>
nnoremap <buffer> <Leader>jt :call JustifyCurrentLine()<cr>
endif
"

View File

@@ -45,6 +45,8 @@ endif
setlocal comments= commentstring=//\ %s
setlocal suffixesadd=.styl
" Add '-' and '#' to the what makes up a keyword.
" This means that 'e' and 'w' work properly now, for properties
" and valid variable names.

33
ftplugin/tex_LatexBox.vim Normal file
View File

@@ -0,0 +1,33 @@
" LaTeX Box plugin for Vim
" Maintainer: David Munger
" Email: mungerd@gmail.com
" Version: 0.9.6
if exists('*fnameescape')
function! s:FNameEscape(s)
return fnameescape(a:s)
endfunction
else
function! s:FNameEscape(s)
return a:s
endfunction
endif
if !exists('b:LatexBox_loaded')
let prefix = expand('<sfile>:p:h') . '/latex-box/'
execute 'source ' . s:FNameEscape(prefix . 'common.vim')
execute 'source ' . s:FNameEscape(prefix . 'complete.vim')
execute 'source ' . s:FNameEscape(prefix . 'motion.vim')
execute 'source ' . s:FNameEscape(prefix . 'latexmk.vim')
execute 'source ' . s:FNameEscape(prefix . 'folding.vim')
" added by AH to add main.tex file finder
execute 'source ' . s:FNameEscape(prefix . 'findmain.vim')
execute 'source ' . s:FNameEscape(prefix . 'mappings.vim')
let b:LatexBox_loaded = 1
endif
" vim:fdm=marker:ff=unix:noet:ts=4:sw=4

13
ftplugin/tt2html.vim Normal file
View File

@@ -0,0 +1,13 @@
" Language: TT2 embedded with HTML
" Maintainer: vim-perl <vim-perl@googlegroups.com>
" Homepage: http://github.com/vim-perl/vim-perl
" Bugs/requests: http://github.com/vim-perl/vim-perl/issues
" Last Change: {{LAST_CHANGE}}
" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
finish
endif
" Just use the HTML plugin for now.
runtime! ftplugin/html.vim ftplugin/html_*.vim ftplugin/html/*.vim

10
ftplugin/typescript.vim Normal file
View File

@@ -0,0 +1,10 @@
compiler typescript
setlocal autoindent
setlocal smartindent
setlocal indentexpr&
setlocal cindent
setlocal cino=j1J1
setlocal commentstring=//\ %s

14
ftplugin/xs.vim Normal file
View File

@@ -0,0 +1,14 @@
" Vim filetype plugin file
" Language: XS (Perl extension interface language)
" Maintainer: vim-perl <vim-perl@googlegroups.com>
" Homepage: http://github.com/vim-perl/vim-perl
" Bugs/requests: http://github.com/vim-perl/vim-perl/issues
" Last Change: {{LAST_CHANGE}}
" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
finish
endif
" Just use the C plugin for now.
runtime! ftplugin/c.vim ftplugin/c_*.vim ftplugin/c/*.vim

View File

@@ -53,6 +53,10 @@ if exists("*searchpairpos")
let g:clojure_align_multiline_strings = 0
endif
if !exists('g:clojure_align_subforms')
let g:clojure_align_subforms = 0
endif
function! s:SynIdName()
return synIDattr(synID(line("."), col("."), 0), "name")
endfunction
@@ -144,6 +148,10 @@ if exists("*searchpairpos")
return val
endfunction
function! s:StripNamespaceAndMacroChars(word)
return substitute(a:word, "\\v%(.*/|[#'`~@^,]*)(.*)", '\1', '')
endfunction
function! s:ClojureIsMethodSpecialCaseWorker(position)
" Find the next enclosing form.
call search('\S', 'Wb')
@@ -163,7 +171,8 @@ if exists("*searchpairpos")
call cursor(nextParen)
call search('\S', 'W')
if g:clojure_special_indent_words =~ '\<' . s:CurrentWord() . '\>'
let w = s:StripNamespaceAndMacroChars(s:CurrentWord())
if g:clojure_special_indent_words =~ '\<' . w . '\>'
return 1
endif
@@ -269,7 +278,7 @@ if exists("*searchpairpos")
" metacharacters.
"
" e.g. clojure.core/defn and #'defn should both indent like defn.
let ww = substitute(w, "\\v%(.*/|[#'`~@^,]*)(.*)", '\1', '')
let ww = s:StripNamespaceAndMacroChars(w)
if &lispwords =~ '\V\<' . ww . '\>'
return paren[1] + &shiftwidth - 1
@@ -284,7 +293,7 @@ if exists("*searchpairpos")
call search('\v\_s', 'cW')
call search('\v\S', 'W')
if paren[0] < line(".")
return paren[1] + &shiftwidth - 1
return paren[1] + (g:clojure_align_subforms ? 0 : &shiftwidth - 1)
endif
call search('\v\S', 'bW')

View File

@@ -99,6 +99,16 @@ let s:SYNTAX_COMMENT = 'coffee\%(Comment\|BlockComment\|HeregexComment\)'
" Syntax names for strings and comments
let s:SYNTAX_STRING_COMMENT = s:SYNTAX_STRING . '\|' . s:SYNTAX_COMMENT
" Compatibility code for shiftwidth() as recommended by the docs, but modified
" so there isn't as much of a penalty if shiftwidth() exists.
if exists('*shiftwidth')
let s:ShiftWidth = function('shiftwidth')
else
function! s:ShiftWidth()
return &shiftwidth
endfunction
endif
" Get the linked syntax name of a character.
function! s:SyntaxName(lnum, col)
return synIDattr(synID(a:lnum, a:col, 1), 'name')
@@ -329,16 +339,16 @@ function! GetCoffeeIndent(curlnum)
" Always indent after these operators.
if prevline =~ s:BEGIN_BLOCK_OP
return indent(prevnlnum) + shiftwidth()
return indent(prevnlnum) + s:ShiftWidth()
endif
" Indent if the previous line starts a function block, but don't force
" indenting if the line is non-blank (for empty function bodies.)
if prevline =~ s:FUNCTION
if strlen(getline(a:curlnum)) > indent(a:curlnum)
return min([indent(prevnlnum) + shiftwidth(), indent(a:curlnum)])
return min([indent(prevnlnum) + s:ShiftWidth(), indent(a:curlnum)])
else
return indent(prevnlnum) + shiftwidth()
return indent(prevnlnum) + s:ShiftWidth()
endif
endif
@@ -365,7 +375,7 @@ function! GetCoffeeIndent(curlnum)
endif
" Otherwise indent a level.
return indent(prevnlnum) + shiftwidth()
return indent(prevnlnum) + s:ShiftWidth()
endif
" Check if the previous line starts with a keyword that begins a block.
@@ -374,7 +384,7 @@ function! GetCoffeeIndent(curlnum)
" isn't a single-line statement.
if curline !~ '\C^\<then\>' && !s:SearchCode(prevnlnum, '\C\<then\>') &&
\ prevline !~ s:SINGLE_LINE_ELSE
return indent(prevnlnum) + shiftwidth()
return indent(prevnlnum) + s:ShiftWidth()
else
exec 'return' s:GetDefaultPolicy(a:curlnum)
endif
@@ -383,7 +393,7 @@ function! GetCoffeeIndent(curlnum)
" Indent a dot access if it's the first.
if curline =~ s:DOT_ACCESS
if prevline !~ s:DOT_ACCESS
return indent(prevnlnum) + shiftwidth()
return indent(prevnlnum) + s:ShiftWidth()
else
exec 'return' s:GetDefaultPolicy(a:curlnum)
endif
@@ -396,7 +406,7 @@ function! GetCoffeeIndent(curlnum)
\ s:SearchCode(prevnlnum, '\C\<then\>') &&
\ !s:SearchCode(prevnlnum, s:CONTAINED_THEN)
" Don't force indenting.
return min([indent(a:curlnum), indent(prevnlnum) - shiftwidth()])
return min([indent(a:curlnum), indent(prevnlnum) - s:ShiftWidth()])
else
exec 'return' s:GetDefaultPolicy(a:curlnum)
endif
@@ -410,7 +420,7 @@ function! GetCoffeeIndent(curlnum)
" If inside brackets, indent relative to the brackets, but don't outdent an
" already indented line.
if matchlnum
return max([indent(a:curlnum), indent(matchlnum) + shiftwidth()])
return max([indent(a:curlnum), indent(matchlnum) + s:ShiftWidth()])
endif
" No special rules applied, so use the default policy.

View File

@@ -10,7 +10,7 @@ let b:did_indent = 1
setlocal nosmartindent
setlocal indentexpr=GetElixirIndent(v:lnum)
setlocal indentexpr=GetElixirIndent()
setlocal indentkeys+==end,=else:,=match:,=elsif:,=catch:,=after:,=rescue:
if exists("*GetElixirIndent")
@@ -25,11 +25,13 @@ let s:block_skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" . s:s
let s:block_start = 'do\|fn'
let s:block_middle = 'else\|match\|elsif\|catch\|after\|rescue'
let s:block_end = 'end'
let s:arrow = '^.*->$'
let s:pipeline = '^\s*|>.*$'
let s:indent_keywords = '\<\%(' . s:block_start . '\|' . s:block_middle . '\)$'
let s:deindent_keywords = '^\s*\<\%(' . s:block_end . '\|' . s:block_middle . '\)\>'
let s:indent_keywords = '\<\%(' . s:block_start . '\|' . s:block_middle . '\)$' . '\|' . s:arrow
let s:deindent_keywords = '^\s*\<\%(' . s:block_end . '\|' . s:block_middle . '\)\>' . '\|' . s:arrow
function! GetElixirIndent(...)
function! GetElixirIndent()
let lnum = prevnonblank(v:lnum - 1)
let ind = indent(lnum)
@@ -38,20 +40,60 @@ function! GetElixirIndent(...)
return 0
endif
if synIDattr(synID(v:lnum, 1, 1), "name") !~ '\(Comment\|String\)$'
if getline(lnum) =~ s:indent_keywords .
\ '\|^\s*\%(^.*[\[{(].*[,:]\|.*->\)$'
" TODO: Remove these 2 lines
" I don't know why, but for the test on spec/indent/lists_spec.rb:24.
" Vim is making some mess on parsing the syntax of 'end', it is being
" recognized as 'elixirString' when should be recognized as 'elixirBlock'.
" This forces vim to sync the syntax.
call synID(v:lnum, 1, 1)
syntax sync fromstart
if synIDattr(synID(v:lnum, 1, 1), "name") !~ s:skip_syntax
let current_line = getline(v:lnum)
let last_line = getline(lnum)
let splited_line = split(last_line, '\zs')
let opened_symbol = 0
let opened_symbol += count(splited_line, '[') - count(splited_line, ']')
let opened_symbol += count(splited_line, '{') - count(splited_line, '}')
let ind += opened_symbol * &sw
if last_line =~ s:indent_keywords
let ind += &sw
endif
if getline(v:lnum) =~ s:deindent_keywords
" if line starts with pipeline
" and last line is an attribution
" indents pipeline in same level as attribution
if current_line =~ s:pipeline &&
\ last_line =~ '^[^=]\+=.\+$'
let b:old_ind = ind
let ind = float2nr(matchend(last_line, '=\s*[^ ]') / &sw) * &sw
endif
" if last line starts with pipeline
" and current line doesn't start with pipeline
" returns the indentation before the pipeline
if last_line =~ s:pipeline &&
\ current_line !~ s:pipeline
let ind = b:old_ind
endif
if current_line =~ s:deindent_keywords
let bslnum = searchpair( '\<\%(' . s:block_start . '\):\@!\>',
\ '\<\%(' . s:block_middle . '\):\@!\>\zs',
\ '\<:\@<!' . s:block_end . '\>\zs',
\ 'nbW',
\ s:block_skip )
let ind = indent(bslnum)
endif
" indent case statements '->'
if current_line =~ s:arrow
let ind += &sw
endif
endif
return ind

View File

@@ -1,58 +1,207 @@
" Vim indent file
" Language: Erlang
" Author: Ricardo Catalinas Jiménez <jimenezrick@gmail.com>
" License: Vim license
" Version: 2013/09/11
" Language: Erlang
" Maintainer: Csaba Hoch <csaba.hoch@gmail.com>
" Contributor: Edwin Fine <efine145_nospam01 at usa dot net>
" Contributor: Pawel 'kTT' Salata <rockplayer.pl@gmail.com>
" Last Change: 2010 Aug 30
if !exists('g:erlang_force_use_vimerl_indent')
let g:erlang_force_use_vimerl_indent = 0
endif
if exists('b:did_indent') || (v:version >= 704 && !g:erlang_force_use_vimerl_indent)
finish
else
let b:did_indent = 1
" Only load this indent file when no other was loaded.
if exists("b:did_indent")
finish
endif
let b:did_indent = 1
setlocal indentexpr=ErlangIndent()
setlocal indentkeys=!^F,o,O,=),=},=],=>>,=of,=catch,=after,=end
setlocal indentkeys+==after,=end,=catch,=),=],=}
if exists('*ErlangIndent')
finish
" Only define the functions once.
if exists("*ErlangIndent")
finish
endif
let s:erlang_indent_file = expand('<sfile>:p:h') . '/erlang_indent.erl'
if filewritable(expand('<sfile>:p:h')) == 2
let s:in_fifo = expand('<sfile>:p:h') . '/vimerl_in_fifo.' . getpid()
let s:out_fifo = expand('<sfile>:p:h') . '/vimerl_out_fifo.' . getpid()
else
let s:in_fifo = '/tmp/vimerl_in_fifo.' . getpid()
let s:out_fifo = '/tmp/vimerl_out_fifo.' . getpid()
endif
" The function go through the whole line, analyses it and sets the indentation
" (ind variable).
" l: the number of the line to be examined.
function s:ErlangIndentAfterLine(l)
let i = 0 " the index of the current character in the line
let length = strlen(a:l) " the length of the line
let ind = 0 " how much should be the difference between the indentation of
" the current line and the indentation of the next line?
" e.g. +1: the indentation of the next line should be equal to
" the indentation of the current line plus one shiftwidth
let lastFun = 0 " the last token was a 'fun'
let lastReceive = 0 " the last token was a 'receive'; needed for 'after'
let lastHashMark = 0 " the last token was a 'hashmark'
execute 'silent !mkfifo' s:in_fifo
execute 'silent !mkfifo' s:out_fifo
execute 'silent !' . s:erlang_indent_file s:out_fifo s:in_fifo '&'
" ignore type annotation lines
if a:l =~# '^\s*-type'
return 0
endif
autocmd VimLeave * call <SID>StopIndenter()
while 0<= i && i < length
function s:StopIndenter()
call writefile([], s:out_fifo)
call delete(s:in_fifo)
call delete(s:out_fifo)
" m: the next value of the i
if a:l[i] == '%'
break
elseif a:l[i] == '"'
let m = matchend(a:l,'"\%([^"\\]\|\\.\)*"',i)
let lastReceive = 0
elseif a:l[i] == "'"
let m = matchend(a:l,"'[^']*'",i)
let lastReceive = 0
elseif a:l[i] =~# "[a-z]"
let m = matchend(a:l,".[[:alnum:]_]*",i)
if lastFun
let ind = ind - 1
let lastFun = 0
let lastReceive = 0
elseif a:l[(i):(m-1)] =~# '^\%(case\|if\|try\)$'
let ind = ind + 1
elseif a:l[(i):(m-1)] =~# '^receive$'
let ind = ind + 1
let lastReceive = 1
elseif a:l[(i):(m-1)] =~# '^begin$'
let ind = ind + 2
let lastReceive = 0
elseif a:l[(i):(m-1)] =~# '^end$'
let ind = ind - 2
let lastReceive = 0
elseif a:l[(i):(m-1)] =~# '^after$'
if lastReceive == 0
let ind = ind - 1
else
let ind = ind + 0
endif
let lastReceive = 0
elseif a:l[(i):(m-1)] =~# '^fun$'
let ind = ind + 1
let lastFun = 1
let lastReceive = 0
endif
elseif a:l[i] =~# "[A-Z_]"
let m = matchend(a:l,".[[:alnum:]_]*",i)
let lastReceive = 0
elseif a:l[i] == '$'
let m = i+2
let lastReceive = 0
elseif a:l[i] == "." && (i+1>=length || a:l[i+1]!~ "[0-9]")
let m = i+1
if lastHashMark
let lastHashMark = 0
else
let ind = ind - 1
endif
let lastReceive = 0
elseif a:l[i] == '-' && (i+1<length && a:l[i+1]=='>')
let m = i+2
let ind = ind + 1
let lastReceive = 0
elseif a:l[i] == ';' && a:l[(i):(length)] !~# '.*->.*'
let m = i+1
let ind = ind - 1
let lastReceive = 0
elseif a:l[i] == '#'
let m = i+1
let lastHashMark = 1
elseif a:l[i] =~# '[({[]'
let m = i+1
let ind = ind + 1
let lastFun = 0
let lastReceive = 0
let lastHashMark = 0
elseif a:l[i] =~# '[)}\]]'
let m = i+1
let ind = ind - 1
let lastReceive = 0
else
let m = i+1
endif
let i = m
endwhile
return ind
endfunction
function s:FindPrevNonBlankNonComment(lnum)
let lnum = prevnonblank(a:lnum)
let line = getline(lnum)
" continue to search above if the current line begins with a '%'
while line =~# '^\s*%.*$'
let lnum = prevnonblank(lnum - 1)
if 0 == lnum
return 0
endif
let line = getline(lnum)
endwhile
return lnum
endfunction
function ErlangIndent()
if v:lnum == 1
return 0
else
call writefile([v:lnum] + getline(1, v:lnum), s:out_fifo)
let indent = split(readfile(s:in_fifo)[0])
if len(indent) == 1 || !&expandtab
return indent[0] * &shiftwidth
else
return indent[1]
endif
endif
" Find a non-blank line above the current line.
let lnum = prevnonblank(v:lnum - 1)
" Hit the start of the file, use zero indent.
if lnum == 0
return 0
endif
let prevline = getline(lnum)
let currline = getline(v:lnum)
let ind = indent(lnum) + &sw * s:ErlangIndentAfterLine(prevline)
" special cases:
if prevline =~# '^\s*\%(after\|end\)\>'
let ind = ind + 2*&sw
endif
if currline =~# '^\s*end\>'
let ind = ind - 2*&sw
endif
if currline =~# '^\s*after\>'
let plnum = s:FindPrevNonBlankNonComment(v:lnum-1)
if getline(plnum) =~# '^[^%]*\<receive\>\s*\%(%.*\)\=$'
let ind = ind - 1*&sw
" If the 'receive' is not in the same line as the 'after'
else
let ind = ind - 2*&sw
endif
endif
if prevline =~# '^\s*[)}\]]'
let ind = ind + 1*&sw
endif
if currline =~# '^\s*[)}\]]'
let ind = ind - 1*&sw
endif
if prevline =~# '^\s*\%(catch\)\s*\%(%\|$\)'
let ind = ind + 1*&sw
endif
if currline =~# '^\s*\%(catch\)\s*\%(%\|$\)'
let ind = ind - 1*&sw
endif
if ind<0
let ind = 0
endif
return ind
endfunction
" TODO:
"
" f() ->
" x("foo
" bar")
" ,
" bad_indent.
"
" fun
" init/0,
" bad_indent
"
" #rec
" .field,
" bad_indent

View File

@@ -19,6 +19,9 @@ else
endif
unlet! b:did_indent
" Force HTML indent to not keep state.
let b:html_indent_usestate = 0
if &l:indentexpr == ''
if &l:cindent
let &l:indentexpr = 'cindent(v:lnum)'
@@ -53,7 +56,8 @@ function! GetErubyIndent(...)
else
exe "let ind = ".b:eruby_subtype_indentexpr
" Workaround for Andy Wokula's HTML indent
" Workaround for Andy Wokula's HTML indent. This should be removed after
" some time, since the newest version is fixed in a different way.
if b:eruby_subtype_indentexpr =~# '^HtmlIndent('
\ && exists('b:indent')
\ && type(b:indent) == type({})

380
indent/html.vim Normal file
View File

@@ -0,0 +1,380 @@
" Description: HTML5 and inline SVG indenter
" Changed By: HT de Beer <H.T.de.Beer@gmail.com>
" Last Change: 20121013
" Added the SVG elements to the list of indenting element. SVG elements
" taken from http://www.w3.org/TR/SVG/eltindex.html
"
" Description: html5 (and html4) indenter
" Changed By: Brian Gershon <brian.five@gmail.com>
" Last Change: 30 Jan 2011
"
" 1. Started with vim72 html indent file authored by Johannes Zellner (below)
" 2. Added html5 list as described here:
" http://stackoverflow.com/questions/3232518/how-to-update-vim-to-color-code-new-html-elements
" 3. Added this to a fork of https://github.com/othree/html5.vim
" which already provides nice html5 syntax highlighting.
"
" Description: html indenter
" Author: Johannes Zellner <johannes@zellner.org>
" Last Change: Mo, 05 Jun 2006 22:32:41 CEST
" Restoring 'cpo' and 'ic' added by Bram 2006 May 5
" Globals:
" let g:html_indent_tags = 'html\|p\|time'
" let g:html_exclude_tags = ['html', 'style', 'script', 'body']
" Only load this indent file when no other was loaded.
if exists("b:did_indent")
finish
endif
runtime! indent/javascript.vim
let s:jsindent = &indentexpr
unlet b:did_indent
runtime! indent/css.vim
let s:cssindent = &indentexpr
let b:did_indent = 1
" [-- local settings (must come before aborting the script) --]
setlocal indentexpr=HtmlIndentGet(v:lnum)
setlocal indentkeys=o,O,*<Return>,<>>,{,}
let s:tags = []
" [-- <ELEMENT ? - - ...> --]
call add(s:tags, 'a')
call add(s:tags, 'abbr')
call add(s:tags, 'acronym')
call add(s:tags, 'address')
call add(s:tags, 'b')
call add(s:tags, 'bdo')
call add(s:tags, 'big')
call add(s:tags, 'blockquote')
call add(s:tags, 'button')
call add(s:tags, 'caption')
call add(s:tags, 'center')
call add(s:tags, 'cite')
call add(s:tags, 'code')
call add(s:tags, 'colgroup')
call add(s:tags, 'del')
call add(s:tags, 'dfn')
call add(s:tags, 'dir')
call add(s:tags, 'div')
call add(s:tags, 'dl')
call add(s:tags, 'em')
call add(s:tags, 'fieldset')
call add(s:tags, 'font')
call add(s:tags, 'form')
call add(s:tags, 'frameset')
call add(s:tags, 'h1')
call add(s:tags, 'h2')
call add(s:tags, 'h3')
call add(s:tags, 'h4')
call add(s:tags, 'h5')
call add(s:tags, 'h6')
call add(s:tags, 'i')
call add(s:tags, 'iframe')
call add(s:tags, 'ins')
call add(s:tags, 'kbd')
call add(s:tags, 'label')
call add(s:tags, 'legend')
call add(s:tags, 'li')
call add(s:tags, 'map')
call add(s:tags, 'menu')
call add(s:tags, 'noframes')
call add(s:tags, 'noscript')
call add(s:tags, 'object')
call add(s:tags, 'ol')
call add(s:tags, 'optgroup')
call add(s:tags, 'p')
" call add(s:tags, 'pre')
call add(s:tags, 'q')
call add(s:tags, 's')
call add(s:tags, 'samp')
call add(s:tags, 'script')
call add(s:tags, 'select')
call add(s:tags, 'small')
call add(s:tags, 'span')
call add(s:tags, 'strong')
call add(s:tags, 'style')
call add(s:tags, 'sub')
call add(s:tags, 'sup')
call add(s:tags, 'table')
call add(s:tags, 'textarea')
call add(s:tags, 'title')
call add(s:tags, 'tt')
call add(s:tags, 'u')
call add(s:tags, 'ul')
call add(s:tags, 'var')
" New HTML 5 elements
call add(s:tags, 'article')
call add(s:tags, 'aside')
call add(s:tags, 'audio')
call add(s:tags, 'canvas')
call add(s:tags, 'datalist')
call add(s:tags, 'details')
call add(s:tags, 'figcaption')
call add(s:tags, 'figure')
call add(s:tags, 'footer')
call add(s:tags, 'header')
call add(s:tags, 'hgroup')
call add(s:tags, 'main')
call add(s:tags, 'mark')
call add(s:tags, 'meter')
call add(s:tags, 'nav')
call add(s:tags, 'output')
call add(s:tags, 'progress')
call add(s:tags, 'rp')
call add(s:tags, 'rt')
call add(s:tags, 'ruby')
call add(s:tags, 'section')
call add(s:tags, 'summary')
call add(s:tags, 'time')
call add(s:tags, 'video')
call add(s:tags, 'bdi')
call add(s:tags, 'data')
" Web Component
call add(s:tags, 'template')
" Common inline used SVG elements
call add(s:tags, 'clipPath')
call add(s:tags, 'defs')
call add(s:tags, 'desc')
call add(s:tags, 'filter')
call add(s:tags, 'foreignObject')
call add(s:tags, 'g')
call add(s:tags, 'linearGradient')
call add(s:tags, 'marker')
call add(s:tags, 'mask')
call add(s:tags, 'pattern')
call add(s:tags, 'radialGradient')
call add(s:tags, 'svg')
call add(s:tags, 'switch')
call add(s:tags, 'symbol')
call add(s:tags, 'text')
call add(s:tags, 'textPath')
call add(s:tags, 'tref')
call add(s:tags, 'tspan')
call add(s:tags, 'html')
call add(s:tags, 'head')
call add(s:tags, 'body')
call add(s:tags, 'thead')
call add(s:tags, 'tbody')
call add(s:tags, 'tfoot')
call add(s:tags, 'tr')
call add(s:tags, 'th')
call add(s:tags, 'td')
let s:omittable = [
\ ['address', 'article', 'aside', 'blockquote', 'dir', 'div', 'dl', 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'menu', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'],
\ ['dt', 'dd'],
\ ['li'],
\ ['thead', 'tbody', 'tfoot'],
\ ['th', 'td'],
\]
if exists('g:html_exclude_tags')
for tag in g:html_exclude_tags
call remove(s:tags, index(s:tags, tag))
endfor
endif
let s:html_indent_tags = join(s:tags, '\|')
if exists('g:html_indent_tags')
let s:html_indent_tags = s:html_indent_tags.'\|'.g:html_indent_tags
endif
let s:cpo_save = &cpo
set cpo-=C
" [-- count indent-increasing tags of line a:lnum --]
fun! <SID>HtmlIndentOpen(lnum, pattern)
let s = substitute('x'.getline(a:lnum),
\ '.\{-}\(\(<\)\('.a:pattern.'\)\>\)', "\1", 'g')
let s = substitute(s, "[^\1].*$", '', '')
return strlen(s)
endfun
" [-- count indent-decreasing tags of line a:lnum --]
fun! <SID>HtmlIndentClose(lnum, pattern)
let s = substitute('x'.getline(a:lnum),
\ '.\{-}\(\(<\)/\('.a:pattern.'\)\>>\)', "\1", 'g')
let s = substitute(s, "[^\1].*$", '', '')
return strlen(s)
endfun
" [-- count indent-increasing '{' of (java|css) line a:lnum --]
fun! <SID>HtmlIndentOpenAlt(lnum)
return strlen(substitute(getline(a:lnum), '[^{]\+', '', 'g'))
endfun
" [-- count indent-decreasing '}' of (java|css) line a:lnum --]
fun! <SID>HtmlIndentCloseAlt(lnum)
return strlen(substitute(getline(a:lnum), '[^}]\+', '', 'g'))
endfun
" [-- return the sum of indents respecting the syntax of a:lnum --]
fun! <SID>HtmlIndentSum(lnum, style)
if a:style == match(getline(a:lnum), '^\s*</')
if a:style == match(getline(a:lnum), '^\s*</\<\('.s:html_indent_tags.'\)\>')
let open = <SID>HtmlIndentOpen(a:lnum, s:html_indent_tags)
let close = <SID>HtmlIndentClose(a:lnum, s:html_indent_tags)
if 0 != open || 0 != close
return open - close
endif
endif
endif
if '' != &syntax &&
\ synIDattr(synID(a:lnum, 1, 1), 'name') =~ '\(css\|java\).*' &&
\ synIDattr(synID(a:lnum, strlen(getline(a:lnum)), 1), 'name')
\ =~ '\(css\|java\).*'
if a:style == match(getline(a:lnum), '^\s*}')
return <SID>HtmlIndentOpenAlt(a:lnum) - <SID>HtmlIndentCloseAlt(a:lnum)
endif
endif
return 0
endfun
fun! HtmlIndentGet(lnum)
" Find a non-empty line above the current line.
let lnum = prevnonblank(a:lnum - 1)
" Hit the start of the file, use zero indent.
if lnum == 0
return 0
endif
let restore_ic = &ic
setlocal ic " ignore case
" [-- special handling for <pre>: no indenting --]
if getline(a:lnum) =~ '\c</pre>'
\ || 0 < searchpair('\c<pre>', '', '\c</pre>', 'nWb')
\ || 0 < searchpair('\c<pre>', '', '\c</pre>', 'nW')
" we're in a line with </pre> or inside <pre> ... </pre>
if restore_ic == 0
setlocal noic
endif
return -1
endif
" [-- special handling for <javascript>: use cindent --]
let js = '<script'
let jse = '</script>'
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" by Tye Zdrojewski <zdro@yahoo.com>, 05 Jun 2006
" ZDR: This needs to be an AND (we are 'after the start of the pair' AND
" we are 'before the end of the pair'). Otherwise, indentation
" before the start of the script block will be affected; the end of
" the pair will still match if we are before the beginning of the
" pair.
"
if 0 < searchpair(js, '', jse, 'nWb')
\ && 0 < searchpair(js, '', jse, 'nW')
" we're inside javascript
if getline(searchpair(js, '', '</script>', 'nWb')) !~ '<script [^>]*type=["'']\?text\/\(html\|template\)'
\ && getline(lnum) !~ js && getline(a:lnum) !~ jse
if restore_ic == 0
setlocal noic
endif
if s:jsindent == ''
return cindent(a:lnum)
else
execute 'let ind = ' . s:jsindent
return ind
endif
endif
if getline(a:lnum) =~ jse
return indent(searchpair(js, '', jse, 'nWb'))
endif
endif
let css = '<style'
let csse = '</style>'
if 0 < searchpair(css, '', csse, 'nWb')
\ && 0 < searchpair(css, '', csse, 'nW')
" we're inside style
if getline(lnum) !~ css && getline(a:lnum) !~ csse
if restore_ic == 0
setlocal noic
endif
if s:cssindent == ''
return cindent(a:lnum)
else
execute 'let ind = ' . s:cssindent
return ind
endif
endif
if getline(a:lnum) =~ csse
return indent(searchpair(css, '', csse, 'nWb'))
endif
endif
if getline(lnum) =~ '\c</pre>'
" line before the current line a:lnum contains
" a closing </pre>. --> search for line before
" starting <pre> to restore the indent.
let preline = prevnonblank(search('\c<pre>', 'bW') - 1)
if preline > 0
if restore_ic == 0
setlocal noic
endif
if 0 == match(getline(a:lnum), '^\s*</')
return indent(preline) - (1*&sw)
else
return indent(preline)
endif
endif
endif
let ind = <SID>HtmlIndentSum(lnum, -1)
let ind = ind + <SID>HtmlIndentSum(a:lnum, 0)
" Fix for conditional comment
if getline(a:lnum) =~ '\c<!--.*<\(html\|body\).*-->'
let ind = ind - 1
endif
let lind = indent(lnum)
" for tags in s:omittable
" let tags_exp = '<\(' . join(tags, '\|') . '\)>'
" let close_tags_exp = '</\(' . join(tags, '\|') . '\)>'
" if getline(a:lnum) =~ tags_exp
" let block_start = search('^'.repeat(' ', lind + (&sw * ind - 1)).'\S' , 'bnW')
" let prev_tag = search(tags_exp, 'bW', block_start)
" let prev_closetag = search(close_tags_exp, 'W', a:lnum)
" if prev_tag && !prev_closetag
" let ind = ind - 1
" endif
" endif
" if getline(a:lnum) =~ '</\w\+>'
" let block_start = search('^'.repeat(' ', lind + (&sw * ind - 1)).'\S' , 'bnW')
" let prev_tag = search(tags_exp, 'bW', block_start)
" let prev_closetag = search(close_tags_exp, 'W', a:lnum)
" if prev_tag && !prev_closetag
" let ind = ind - 1
" endif
" endif
" endfor
if restore_ic == 0
setlocal noic
endif
return lind + (&sw * ind)
endfun
let &cpo = s:cpo_save
unlet s:cpo_save
" [-- EOF <runtime>/indent/html.vim --]

Some files were not shown because too many files have changed in this diff Show More