I was looking for a quick way to autoformat/pretty-print JSON in Vim the other day and found this great little command on Stack Overflow: :%!python -m json.tool
That sent me on a search for a list of other Python tools to pretty-print common web files, but I couldn't find much. Is there a goo开发者_运维技巧d resource/list of Python tools that they find particularly useful for cleaning up poorly formatted web stuff inside Vim (e.g. HTML, XML, JavaScript, etc.)?
Python
Are you just looking for a resource for Python one-liners? You could browse through the Python standard library documentation to find more inspiration.
Or simply google "python one-liners json.tool" to find additional resources. For example, this Reddit post: Suggestion for a Python blogger: figure out what what all the stdlib main functionality is, and document it
Command line
Vim supports more than just Python (e.g. HTML Tidy as Keith suggested). Any tool that can accept pipe/standard input will integrate well with Vim.
The %
command just picks a range that contains the entire file, and !
filters that range through an external program.
See :help :%
and :help :!
For XHTML and XML files you can use tidy.
:%!tidy -i -asxhtml -utf8
:`<,`>!tidy -i -xml -utf8
The last one works on visual selections.
Vim has a command to do it, =
(equal), like in ggvG=
will reindent the whole file. Try :help =
for more info about how to use functions and external programs with =
. The default configuration uses internal indenting rules which works for most file types.
There are loads of good tools that are can convert text between the two formats:
par: for hard line wrapping.
pandoc: for HTML, LaTeX, rst, and Markdown
autopep8: for parsing Python code into an AST and spitting it out as pep8 compliant.
...
Vim is designed to make use of such utilities by the powerful formatprg
settings. That by default is mapped to the gq operator. It works well with Vim motions, Vim text objects, selections, etc.
For instance, I use the setting below for on my Python files
au FileType python setlocal formatprg=autopep8\ --indent-size\ 0\ -
John MacFarlne has a good article about creating a specialised script using pandoc which you could stick in your vimrc.
!autopep8 -i %
seems to work fine in vim
. The -i
switch is to over-write the existing file in place. Use more @ autopep8 --help
.
There is a vim
plugin for this if you really are thinking of being a power user. Outside of vim
you can test it with autopep8 -diff {filename} or autopep8 {filename}
.
精彩评论