I added a shortcut in VIM so that I can press Esc
and ,pt
to get the automatic sql formatting from sqlformat command.
Taken from Can VIM autoindent SQL?.
"autocmd FileType sql call SqlFormatter()
nnoremap call SqlFormatter()
augroup end
function SqlFormatter()
set noai
" set mappings...
map ,pt :%!sqlformat --reindent --indent_width 4 --keywords upper --identifiers lower -<CR>
endfunction
I commented out autocmd FileType sql call SqlFormatter()
and replaced it with nnoremap call SqlFormatter()
to have it available in any file since often, I have SQL code that is embedded in another language and I thought I might perhaps use it only on a selection of the file.
What I need: In visual mode of vim (Esc
+v
), I want to mark something, and then press a shortcut of my choice to reformat only the marked code.
Is there away to make vim treat the selection as its own file perhaps, like its own buffer, so that sqlformat?
Another way would be to change sqlformat: add a parameter that allows applying it only to a selection. Such a parameter is not yet there:
usage: sqlformat [OPTIONS] FILE, ...
Format FILE according to OPTIONS. Use "-" as FILE to read from stdin.
positional arguments:
filename
optional arguments:
-h, --help show this help message and exit
-o FILE, --outfile FILE
write output to FILE (defaults to stdout)
--version show program's version number and exit
Formatting Options:
-k CHOICE, --keywords CHOICE
change case of keywords, CHOICE is one of "upper", "lower", "capitalize"
-i CHOICE, --identifiers CHOICE
change case of identifiers, CHOICE is one of "upper", "lower", "capitalize"
-l LANG, --language LANG
output a snippet in programming language LANG, choices are "python", "php"
--strip-comments remove comments
-r, --reindent reindent statements
--indent_width INDENT_WIDTH
indentation width (defaults to 2 spaces)
-a, --reindent_aligned
reindent statements to aligned format
-s, --use_space_around_operators
place spaces around mathematical operators
--wrap_after WRAP_AFTER
Column after which lists should be wrapped
--comma_first COMMA_FIRST
Insert linebreak before comma (default False)
--encoding ENCODING Specify the input encoding (default utf-8)
- Would it perhaps work with plugins/wrappers like the vim plugin "vim-autoformat" and/or "sqlparse" within VIM? (see the link above)