Skip to content

Commit

Permalink
Change JSON provider to sheerun/vim-json, closes #51
Browse files Browse the repository at this point in the history
  • Loading branch information
sheerun committed Mar 9, 2015
1 parent 23913e0 commit f24fecc
Show file tree
Hide file tree
Showing 4 changed files with 256 additions and 50 deletions.
2 changes: 1 addition & 1 deletion build
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ PACKS="
jade:digitaltoad/vim-jade
jasmine:glanotte/vim-jasmine
javascript:pangloss/vim-javascript
json:leshill/vim-json
json:sheerun/vim-json
jst:briancollins/vim-jst
latex:LaTeX-Box-Team/LaTeX-Box
less:groenewege/vim-less
Expand Down
7 changes: 1 addition & 6 deletions ftdetect/polyglot.vim
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,7 @@ fun! s:SelectJavascript()
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
autocmd BufNewFile,BufRead *.jsonp set filetype=json
au BufNewFile,BufRead *.ejs set filetype=jst
au BufNewFile,BufRead *.jst set filetype=jst
au BufNewFile,BufRead *.hamljs set filetype=jst
Expand Down
169 changes: 169 additions & 0 deletions indent/json.vim
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
" Vim indent file
" Language: JSON
" Mantainer: Eli Parra <[email protected]> https://github.com/elzr/vim-json
" Last Change: 2014-05-13: merged Fix for square bracket matching by Jakar
" https://github.com/jakar/vim-json/commit/20b650e22aa750c4ab6a66aa646bdd95d7cd548a#diff-e81fc111b2052e306d126bd9989f7b7c
" Original Author: Rogerz Zhang <rogerz.zhang at gmail.com> http://github.com/rogerz/vim-json
" Acknowledgement: Based off of vim-javascript maintained by Darrick Wiebe
" http://www.vim.org/scripts/script.php?script_id=2765

" 0. Initialization {{{1
" =================

" Only load this indent file when no other was loaded.
if exists("b:did_indent")
finish
endif
let b:did_indent = 1

setlocal nosmartindent

" Now, set up our indentation expression and keys that trigger it.
setlocal indentexpr=GetJSONIndent()
setlocal indentkeys=0{,0},0),0[,0],!^F,o,O,e

" Only define the function once.
if exists("*GetJSONIndent")
finish
endif

let s:cpo_save = &cpo
set cpo&vim

" 1. Variables {{{1
" ============

let s:line_term = '\s*\%(\%(\/\/\).*\)\=$'
" Regex that defines blocks.
let s:block_regex = '\%({\)\s*\%(|\%([*@]\=\h\w*,\=\s*\)\%(,\s*[*@]\=\h\w*\)*|\)\=' . s:line_term

" 2. Auxiliary Functions {{{1
" ======================

" Check if the character at lnum:col is inside a string.
function s:IsInString(lnum, col)
return synIDattr(synID(a:lnum, a:col, 1), 'name') == jsonString
endfunction

" Find line above 'lnum' that isn't empty, or in a string.
function s:PrevNonBlankNonString(lnum)
let lnum = prevnonblank(a:lnum)
while lnum > 0
" If the line isn't empty or in a string, end search.
let line = getline(lnum)
if !(s:IsInString(lnum, 1) && s:IsInString(lnum, strlen(line)))
break
endif
let lnum = prevnonblank(lnum - 1)
endwhile
return lnum
endfunction

" Check if line 'lnum' has more opening brackets than closing ones.
function s:LineHasOpeningBrackets(lnum)
let open_0 = 0
let open_2 = 0
let open_4 = 0
let line = getline(a:lnum)
let pos = match(line, '[][(){}]', 0)
while pos != -1
let idx = stridx('(){}[]', line[pos])
if idx % 2 == 0
let open_{idx} = open_{idx} + 1
else
let open_{idx - 1} = open_{idx - 1} - 1
endif
let pos = match(line, '[][(){}]', pos + 1)
endwhile
return (open_0 > 0) . (open_2 > 0) . (open_4 > 0)
endfunction

function s:Match(lnum, regex)
let col = match(getline(a:lnum), a:regex) + 1
return col > 0 && !s:IsInString(a:lnum, col) ? col : 0
endfunction

" 3. GetJSONIndent Function {{{1
" =========================

function GetJSONIndent()
" 3.1. Setup {{{2
" ----------

" Set up variables for restoring position in file. Could use v:lnum here.
let vcol = col('.')

" 3.2. Work on the current line {{{2
" -----------------------------

" Get the current line.
let line = getline(v:lnum)
let ind = -1

" If we got a closing bracket on an empty line, find its match and indent
" according to it.
let col = matchend(line, '^\s*[]}]')

if col > 0 && !s:IsInString(v:lnum, col)
call cursor(v:lnum, col)
let bs = strpart('{}[]', stridx('}]', line[col - 1]) * 2, 2)

let pairstart = escape(bs[0], '[')
let pairend = escape(bs[1], ']')
let pairline = searchpair(pairstart, '', pairend, 'bW')

if pairline > 0
let ind = indent(pairline)
else
let ind = virtcol('.') - 1
endif

return ind
endif

" If we are in a multi-line string, don't do anything to it.
if s:IsInString(v:lnum, matchend(line, '^\s*') + 1)
return indent('.')
endif

" 3.3. Work on the previous line. {{{2
" -------------------------------

let lnum = prevnonblank(v:lnum - 1)

if lnum == 0
return 0
endif

" Set up variables for current line.
let line = getline(lnum)
let ind = indent(lnum)

" If the previous line ended with a block opening, add a level of indent.
" if s:Match(lnum, s:block_regex)
" return indent(lnum) + shiftwidth()
" endif

" If the previous line contained an opening bracket, and we are still in it,
" add indent depending on the bracket type.
if line =~ '[[({]'
let counts = s:LineHasOpeningBrackets(lnum)
if counts[0] == '1' || counts[1] == '1' || counts[2] == '1'
return ind + shiftwidth()
else
call cursor(v:lnum, vcol)
end
endif

" }}}2

return ind
endfunction

" }}}1

let &cpo = s:cpo_save
unlet s:cpo_save

" vim:set sw=2 sts=2 ts=8 noet:

128 changes: 85 additions & 43 deletions syntax/json.vim
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
" Vim syntax file
" Language: JSON
" Maintainer: Jeroen Ruigrok van der Werven <[email protected]>
" Last Change: 2009-06-16
" Version: 0.4
" {{{1

" Syntax setup {{{2
" For version 5.x: Clear all syntax items
" For version 6.x: Quit when a syntax file was already loaded
" Maintainer: Eli Parra <[email protected]> https://github.com/elzr/vim-json
" Last Change: 2014-12-20 Load ftplugin/json.vim

if !exists("main_syntax")
if version < 600
Expand All @@ -18,60 +12,108 @@ if !exists("main_syntax")
let main_syntax = 'json'
endif

" Syntax: Strings {{{2
syn region jsonString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=jsonEscape
syntax match jsonNoise /\%(:\|,\)/

" Syntax: Strings
" Separated into a match and region because a region by itself is always greedy
syn match jsonStringMatch /"\([^"]\|\\\"\)\+"\ze[[:blank:]\r\n]*[,}\]]/ contains=jsonString
syn region jsonString oneline matchgroup=jsonQuote start=/"/ skip=/\\\\\|\\"/ end=/"/ concealends contains=jsonEscape contained

" Syntax: JSON does not allow strings with single quotes, unlike JavaScript.
syn region jsonStringSQ start=+'+ skip=+\\\\\|\\"+ end=+'+
syn region jsonStringSQError oneline start=+'+ skip=+\\\\\|\\"+ end=+'+

" Syntax: JSON Keywords
" Separated into a match and region because a region by itself is always greedy
syn match jsonKeywordMatch /"\([^"]\|\\\"\)\+"[[:blank:]\r\n]*\:/ contains=jsonKeyword
syn region jsonKeyword matchgroup=jsonQuote start=/"/ end=/"\ze[[:blank:]\r\n]*\:/ contains=jsonEscape contained

" Syntax: Escape sequences {{{3
" Syntax: Escape sequences
syn match jsonEscape "\\["\\/bfnrt]" contained
syn match jsonEscape "\\u\x\{4}" contained

" Syntax: Strings should always be enclosed with quotes.
syn match jsonNoQuotes "\<\a\+\>"
" Syntax: Numbers
syn match jsonNumber "-\=\<\%(0\|[1-9]\d*\)\%(\.\d\+\)\=\%([eE][-+]\=\d\+\)\=\>\ze[[:blank:]\r\n]*[,}\]]"

" Syntax: Numbers {{{2
syn match jsonNumber "-\=\<\%(0\|[1-9]\d*\)\%(\.\d\+\)\=\%([eE][-+]\=\d\+\)\=\>"
" ERROR WARNINGS **********************************************
" Syntax: Strings should always be enclosed with quotes.
syn match jsonNoQuotesError "\<[[:alpha:]][[:alnum:]]*\>"
syn match jsonTripleQuotesError /"""/

" Syntax: An integer part of 0 followed by other digits is not allowed.
syn match jsonNumError "-\=\<0\d\.\d*\>"

" Syntax: Boolean {{{2
syn keyword jsonBoolean true false
" Syntax: Decimals smaller than one should begin with 0 (so .1 should be 0.1).
syn match jsonNumError "\:\@<=[[:blank:]\r\n]*\zs\.\d\+"

" Syntax: No comments in JSON, see http://stackoverflow.com/questions/244777/can-i-comment-a-json-file
syn match jsonCommentError "//.*"
syn match jsonCommentError "\(/\*\)\|\(\*/\)"

" Syntax: No semicolons in JSON
syn match jsonSemicolonError ";"

" Syntax: Null {{{2
syn keyword jsonNull null
" Syntax: No trailing comma after the last element of arrays or objects
syn match jsonTrailingCommaError ",\_s*[}\]]"

" Syntax: Braces {{{2
syn match jsonBraces "[{}\[\]]"
" Syntax: Watch out for missing commas between elements
syn match jsonMissingCommaError /\("\|\]\|\d\)\zs\_s\+\ze"/
syn match jsonMissingCommaError /\(\]\|\}\)\_s\+\ze"/ "arrays/objects as values
syn match jsonMissingCommaError /}\_s\+\ze{/ "objects as elements in an array
syn match jsonMissingCommaError /\(true\|false\)\_s\+\ze"/ "true/false as value

" Define the default highlighting. {{{1
" For version 5.7 and earlier: only when not done already
" For version 5.8 and later: only when an item doesn't have highlighting yet
" ********************************************** END OF ERROR WARNINGS
" Allowances for JSONP: function call at the beginning of the file,
" parenthesis and semicolon at the end.
" Function name validation based on
" http://stackoverflow.com/questions/2008279/validate-a-javascript-function-name/2008444#2008444
syn match jsonPadding "\%^[[:blank:]\r\n]*[_$[:alpha:]][_$[:alnum:]]*[[:blank:]\r\n]*("
syn match jsonPadding ");[[:blank:]\r\n]*\%$"

" Syntax: Boolean
syn match jsonBoolean /\(true\|false\)\(\_s\+\ze"\)\@!/

" Syntax: Null
syn keyword jsonNull null

" Syntax: Braces
syn region jsonFold matchgroup=jsonBraces start="{" end=/}\(\_s\+\ze\("\|{\)\)\@!/ transparent fold
syn region jsonFold matchgroup=jsonBraces start="\[" end=/]\(\_s\+\ze"\)\@!/ transparent fold

" Define the default highlighting.
if version >= 508 || !exists("did_json_syn_inits")
if version < 508
let did_json_syn_inits = 1
command -nargs=+ HiLink hi link <args>
else
command -nargs=+ HiLink hi def link <args>
endif
HiLink jsonString String
HiLink jsonEscape Special
HiLink jsonNumber Number
HiLink jsonBraces Operator
HiLink jsonNull Function
HiLink jsonBoolean Boolean

HiLink jsonNumError Error
HiLink jsonStringSQ Error
HiLink jsonNoQuotes Error
delcommand HiLink
hi def link jsonPadding Operator
hi def link jsonString String
hi def link jsonTest Label
hi def link jsonEscape Special
hi def link jsonNumber Number
hi def link jsonBraces Delimiter
hi def link jsonNull Function
hi def link jsonBoolean Boolean
hi def link jsonKeyword Label

hi def link jsonNumError Error
hi def link jsonCommentError Error
hi def link jsonSemicolonError Error
hi def link jsonTrailingCommaError Error
hi def link jsonMissingCommaError Error
hi def link jsonStringSQError Error
hi def link jsonNoQuotesError Error
hi def link jsonTripleQuotesError Error
hi def link jsonQuote Quote
hi def link jsonNoise Noise
endif

let b:current_syntax = "json"
if main_syntax == 'json'
unlet main_syntax
endif

" Vim settings {{{2
" Vim settings
" vim: ts=8 fdm=marker

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

0 comments on commit f24fecc

Please sign in to comment.