1
0
Fork 0
mirror of synced 2024-12-24 07:43:20 -05:00

add vim-json

This commit is contained in:
Chris Hu 2016-08-24 08:56:12 +08:00 committed by Huaishun Hu
parent 75e20d6539
commit 7762fafeb7
9 changed files with 553 additions and 0 deletions

11
sources_non_forked/vim-json/.gitignore vendored Normal file
View file

@ -0,0 +1,11 @@
/index.php
# Ignore vim files
*~
*.swp
*.swo
*.fuse_hidden*
*.pxm
*.DS_Store
/video/*
/screenshots/*

View file

@ -0,0 +1,3 @@
autocmd BufNewFile,BufRead *.json setlocal filetype=json
autocmd BufNewFile,BufRead *.jsonp setlocal filetype=json
autocmd BufNewFile,BufRead *.geojson setlocal filetype=json

View file

@ -0,0 +1,38 @@
" Vim syntax file
" Language: JSON
" Maintainer: Eli Parra <eli@elzr.com> https://github.com/elzr/vim-json
" Last Change: 2014-05-20 added warning toggle
"uncomment to enable folding of `{...}` and `[...]` blocks
"setlocal foldmethod=syntax
"conceal by default
if !exists("g:vim_json_syntax_conceal")
let g:vim_json_syntax_conceal = 1
end
"have warnings by default
if !exists("g:vim_json_warnings")
let g:vim_json_warnings = 1
end
"set concealcursor blank by default
"this should turn off the concealing in the current line (where the cursor is at),
"on all modes (normal, visual, insert)
if !exists("g:vim_json_syntax_concealcursor")
let g:vim_json_syntax_concealcursor = ""
end
if has('conceal')
if (g:vim_json_syntax_conceal == 1)
"level 2 means concealed text gets completely hidden unless a
"replacement is defined (none is defined by us)
setlocal conceallevel=2
let &l:concealcursor = g:vim_json_syntax_concealcursor
else
"level 0 means text is shown normally = no concealing
setlocal conceallevel=0
endif
"maybe g:vim_json_syntax_conceal could be settable to 0,1,2 to map
"directly to vim's conceallevels? unsure if anyone cares
endif

View file

@ -0,0 +1,177 @@
" Vim indent file
" Language: JSON
" Mantainer: Eli Parra <eli@elzr.com> 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)
" if exists('*shiftwidth')
" return indent(lnum) + shiftwidth()
" else
" return indent(lnum) + &sw
" endif
" 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'
if exists('*shiftwidth')
return ind + shiftwidth()
else
return ind + &sw
endif
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:

View file

@ -0,0 +1,107 @@
// this comment should be highlighted as an error
{
unquotedKeyword:'singleQuotedString',
'singleQuotedKeyword':true,
"decimalCantStartWithPeriod":.1,
"semicolonAtEndOfThisObject":"trailingComma",
};
//even with concealment, strings and numbers & booleans are distinct
{
"string": "this is a string, with a escaped \" inside",
"string": "500",
"NOT a string": 500,
"string": "true",
"NOT a string": true
}
// normative JSON examples from http://json.org/example.html
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
//missing comma errors
{
"object1": "missingComma"
"object2": "value"
}
[
{ "object1": 1 }
{ "object2": 2 }
]
{
"object1": []
"object2": []
}
{
"object1": {}
"object2": []
}
{
"object1": true
"object2": 2
}
//this file is deliberately mis-indented, try gg=G to indent it properly

View file

@ -0,0 +1,8 @@
whañteverJavascriptName ( {
"success":true,
"url":"http://google.com",
"shortUrl":"http://b1t.co/54"
});

View file

@ -0,0 +1,11 @@
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 and https://twitter.com/ashemedai/status/295062705193246720 for public acknowledgement of the MIT license as prompted by this issue https://github.com/elzr/vim-json/issues/6

View file

@ -0,0 +1,61 @@
Better JSON for VIM
===================
*Distinct highlighting of keywords vs values, JSON-specific (non-JS) warnings, quote concealing.*
![JSON syntax coloring](https://cloud.githubusercontent.com/assets/183877/7018898/98e428e0-dccf-11e4-9ab8-c554b3556155.jpg)
Customization of Jeroen Ruigrok van der Werven's [vim-json highlighting script](http://www.vim.org/scripts/script.php?script_id=1945) with Rogerz Zhang's [indent script](https://github.com/vim-scripts/vim-json-bundle).
[Pathogen-friendly.](https://github.com/tpope/vim-pathogen) [Vundle-friendly too.](https://github.com/elzr/vim-json/issues/25) ([Or install it manually.](https://github.com/elzr/vim-json/issues/52))
Specific customizations
-----------------------
* Added distinct **highlighting** for keywords vs values! (This is what made me start this plugin.)
* Added **concealing** of double quotes, for a minimalist [CoffeeScript](http://coffeescript.org/)-inspired look ([CSON](https://github.com/bevry/cson)!).
* ![image](https://cloud.githubusercontent.com/assets/183877/6786803/18143984-d154-11e4-841c-134241f951ae.png)<br> [Strings are colored differently than numbers & booleans.](https://github.com/elzr/vim-json/issues/37) The disambiguating purpose of double quotes is thus achieved with colors for a cleaner look.
* *This requires Vim 7.3+.* To disable it add `let g:vim_json_syntax_conceal = 0` to your `.vimrc`.
* Added **folding** of `{...}` and `[...]` blocks. To enable it `:setlocal foldmethod=syntax` (do it permanently on the `ftplugin/json.vim` file).
* **JSON-specific warnings** (red highlights):
* Warn about *no-quotes* in keywords and *single-quotes* in keywords and values.
* Warn about *decimals* smaller than 1 that don't start with a 0 (`.1` gives a warning, it should be `0.1`).
* Warn about *comments* `//` and *trailing semicolons* `;`.
* Warn about *[missing commas](https://github.com/elzr/vim-json/issues/18)* between elements of an object [and elsewhere](https://github.com/elzr/vim-json/issues/34).
* Warn about *trailing commas* after the last element in arrays or objects.
* (All warnings can be turned off with a `let g:vim_json_warnings=0` in your `vimrc`.)
* Recognize `.jsonp` file type. In [JSONP](http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about), the wrapping function call at the beginning and the closing semicolon are recognized.
Screenshots
-----------
**No syntax coloring**: wall of text.<br>![No syntax coloring](https://cloud.githubusercontent.com/assets/183877/7018892/8c9965a0-dccf-11e4-9790-0e815605e3a9.jpg)
**Javascript (or for that matter, the standard json.vim) syntax coloring**: Barely an improvement from no syntax coloring.<br>![Javascript syntax coloring](https://cloud.githubusercontent.com/assets/183877/7018893/906e67c0-dccf-11e4-89b1-11c3cfe9e2ef.jpg)
**Better JSON syntax coloring**: a more meaningful, distinct and elegant presentation.<br>![JSON syntax coloring](https://cloud.githubusercontent.com/assets/183877/7018894/95fd2c1c-dccf-11e4-8cbc-0f6588f9d060.jpg)
Why use separate JSON highlighting instead of just Javascript?
--------------------------------------------------------------
Here's 2 compelling reasons:
1. **All JSON is Javascript but NOT all Javascript is JSON.** So `{property:1}` is invalid because `property` does not have double quotes around it. `{'property':1}` is also invalid, because it's single quoted while the only thing that can placate the JSON specification is double quoting. JSON is even fussy enough that `{"property":.1}` is invalid too, because you should have of course written `{"property":0.1}`. Also, don't even think about [having comments](http://stackoverflow.com/questions/244777/can-i-comment-a-json-file) or semicolons, you guessed it: they're invalid. The point being that your syntax highlighter should warn you about these errors, in realtime, which is something that the Javascript highlighter doesn't (because in Javacript they're not errors!).
2. **Distinct highlighting for keywords.** JSON is an extremely lightweight data format but at its core lies an inescapable conceptual distinction: there are keywords and there are values. There's nothing much to the format besides that, so we might as well display keywords and values differently. This is something that gets lost with Javascript-inspired syntax highlighters, which see keywords as just another string since JSON requires them double quoted. So JSON files remain an impenetrable, indistinct wall of text.
Common problems
---------------
This is the expected behavior of the plugin:
![showcase](http://i.imgur.com/cmL1GNc.gif)
Most trouble, little as it is, has to do with Vim's newfangled concealing, which most people aren't yet familiar with, as it was introduced as recently as Vim 7.3+. If you just don't care for concealing you can easily disable it adding `let g:vim_json_syntax_conceal = 0` to your `.vimrc`.
Concealing is nice for viewing but when you want to edit it should get out of your way seamlessly so you can see the actual code. Thus the **default behavior** *should* be text shown normally on the line your cursor is at, on all modes (normal, visual, insert). If this isn't the case and the concealing doesn't go away (not even in insert mode), you most likely have **an interfering plugin**. You need to look at your `concealcursor` setting (which can be set through this plugin with `g:vim_json_syntax_concealcursor`). The specially overeager [**indentLine**](https://github.com/Yggdroot/indentLine), plugin would require _yet_ an additional `let g:indentLine_noConcealCursor=""` in your `.vimrc` as detailed [here](https://github.com/elzr/vim-json/issues/23#issuecomment-40293049).
It's a good idea to test drive with the files `json-test.json` and `jsonp-test.jsonp` first thing.
Other recommended software
--------------------------
* [JSON Formatter](https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa): Chrome extension for printing JSON and JSONP nicely when you visit it 'directly' in a browser tab.
* [Convert JSON to YAML](http://www.json2yaml.com/): side by side, real-time conversion of the "fat and rigid" JSON to the "skinny and flexible" YAML.

View file

@ -0,0 +1,137 @@
" Vim syntax file
" Language: JSON
" Maintainer: Eli Parra <eli@elzr.com> https://github.com/elzr/vim-json
" Last Change: 2014-12-20 Load ftplugin/json.vim
" Reload the definition of g:vim_json_syntax_conceal
" see https://github.com/elzr/vim-json/issues/42
runtime! ftplugin/json.vim
if !exists("main_syntax")
if version < 600
syntax clear
elseif exists("b:current_syntax")
finish
endif
let main_syntax = 'json'
endif
syntax match jsonNoise /\%(:\|,\)/
" NOTE that for the concealing to work your conceallevel should be set to 2
" 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
if has('conceal') && g:vim_json_syntax_conceal == 1
syn region jsonString oneline matchgroup=jsonQuote start=/"/ skip=/\\\\\|\\"/ end=/"/ concealends contains=jsonEscape contained
else
syn region jsonString oneline matchgroup=jsonQuote start=/"/ skip=/\\\\\|\\"/ end=/"/ contains=jsonEscape contained
endif
" Syntax: JSON does not allow strings with single quotes, unlike JavaScript.
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
if has('conceal') && g:vim_json_syntax_conceal == 1
syn region jsonKeyword matchgroup=jsonQuote start=/"/ end=/"\ze[[:blank:]\r\n]*\:/ concealends contains=jsonEscape contained
else
syn region jsonKeyword matchgroup=jsonQuote start=/"/ end=/"\ze[[:blank:]\r\n]*\:/ contains=jsonEscape contained
endif
" Syntax: Escape sequences
syn match jsonEscape "\\["\\/bfnrt]" contained
syn match jsonEscape "\\u\x\{4}" contained
" Syntax: Numbers
syn match jsonNumber "-\=\<\%(0\|[1-9]\d*\)\%(\.\d\+\)\=\%([eE][-+]\=\d\+\)\=\>\ze[[:blank:]\r\n]*[,}\]]"
" ERROR WARNINGS **********************************************
if (!exists("g:vim_json_warnings") || g:vim_json_warnings==1)
" 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: 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: No trailing comma after the last element of arrays or objects
syn match jsonTrailingCommaError ",\_s*[}\]]"
" 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
endif
" ********************************************** 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")
hi def link jsonPadding Operator
hi def link jsonString String
hi def link jsonTest Label
hi def link jsonEscape Special
hi def link jsonNumber Delimiter
hi def link jsonBraces Delimiter
hi def link jsonNull Function
hi def link jsonBoolean Delimiter
hi def link jsonKeyword Label
if (!exists("g:vim_json_warnings") || g:vim_json_warnings==1)
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
endif
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
" 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