What can you execute on visually selected text in vim?
What are the possible operations (with keyboard shortcuts) that you could execute on a visually selected text? For the simplicity consider this simple piece:
a b cd 1 p
a b cd 2 y
a b cd 3 t
a b cd 4 h
a b cd 5 o
a b cd 6 n
One specific question : is it possible to execute Python/shell commands/scripts on selections?
A couple more specific questions:
1-) How to in-place sort the python column?
2-) How to switch place of columns?
3-) How to increment values? (say. only the numbers greater than 3 in selection)
Thanks.
To do this correctly, you need to use filters and vim's execution mode.
A filter is any standard UNIX program ( sort
, awk
, grep
, cut
, paste
, sed
...) that can read from stdin and write to stdout.
Vim's execution mode lets you read in or replace text with the output of a program. If you make a visual selection (say, using V
or CV
), and hit :
, your command prompt will immediately be :'<,'>
, which means "Apply whatever command follows to the lines included in the visual selection." At this point, you can write !foo
to replace the text with the output of program foo.
For example, to sort the text by the python column, select it, hit :
, and enter !sort -k5
. The whole command will look like :'<,'>!sort -k5
Running it will produce:
a b cd 4 h
a b cd 6 n
a b cd 5 o
a b cd 1 p
a b cd 3 t
a b cd 2 y
For the other two tasks, awk
is your friend. A command like :'<,'>!awk '{ print $1, $3, $2, $4, $5 }'
is will flip the second and third columns (but note that inter-column spacing is collapsed). To increment columns, try something like :'<,'>!awk '{ sub($4, $4+1); print }'
:'<,'>!awk '{ sub($4, $4+1); print }'
.
This question is extremely broad, but to start with look at :help visual-operators
.
Regarding the specific question, check out the plugin EvalSelection.vim, which evaluates source code selected in a visual region in your shell, Python, and several other interpreters. As a very simple example, if you have the following in your Vim buffer:
pwd
echo $SHELL
Select the first line and type <Leader>esp
. Breaking it down:
<Leader>e
is the default key command to invoke EvalSelection.vim. s
specifies that you want to evaluate it using your shell. p
specifies that you want to print the results to Vim's command line.
I get the following output when running the above command: ~/Desktop
with the first line selected. I get /bin/zsh/
using the same command on the second line.
上一篇: 启动vim时脚本的加载顺序是什么?