1

I am looking for some method in vim-script

json.dumps(join(getlines(1,'$'),'\n'))

just like python's json module does

for example open a text file in Vim:

1. var  a=1,
2. b=2,
3. c="";

Call a function should output the following

"var a=1,\nb=2,\nc=\"\""

It is a valid javascript string literal

Anyway, I found a way to achieve that, the following is my code

let b:content = join(getline(1,'$'),"\\n\\\n") . "\\\n"
let b:content = printf("\"%s\"", escape(b:content,"\""))

After the codes above runs, you will get

"var  a=1, \n\
 b=2,\n\
 c=\"\";\
 "

It is a valid multiline javascript string literal, but the disadvantage is this feature will be removed in ECMA-262 3rd Edition according to this post

Community
  • 1
  • 1
wukong
  • 2,430
  • 2
  • 26
  • 33

1 Answers1

0

After read RFC, I wrote this function, maybe helpful

" utility encode to json string
if !exists("*b:json_encode_basestring")
    function b:json_encode_basestring(str)
        let l:ret = a:str
        let l:ret = substitute(l:ret,'\%x5C','\\\\','g')
        let l:ret = substitute(l:ret,'\%x22','\\"','g')
        let l:ret = substitute(l:ret,'\%x2F','/','g')
        let l:ret = substitute(l:ret,'\%x08','\\b','g')
        let l:ret = substitute(l:ret,'\%x0C','\\f','g')
        let l:ret = substitute(l:ret,'\%x0A','\\n','g')
        let l:ret = substitute(l:ret,'\%x0D','\\r','g')
        let l:ret = substitute(l:ret,'\%x09','\\t','g')
        " TODO unicode escape
        " http://www.ietf.org/rfc/rfc4627
        return l:ret
    endfunction
endif

if !exists("*b:json_encode")
    function b:json_encode(lines)
        let l:json = []
        let l:lines = a:lines
        for line in l:lines
            call add(l:json, b:json_encode_basestring(line))
        endfor
        let l:str = join(l:json,'\n').'\n'
        let l:str = printf('"%s"',l:str)
        return l:str
    endfunction
endif

Usage:

:echo b:json_encode(getline(1,'$'))
wukong
  • 2,430
  • 2
  • 26
  • 33