vim shell command integration - vim

Ok, I have rather simple question: How can one bind vim command/hotkey to execute some complicated shell-script?
E.g. I want to optimize base64-inlined images inside css files. I know, that in shell it would be something like:
echo `selection` > /tmp/img.png.b64
base64 -d /tmp/img.png.b64 > /tmp/img.png
optipng -o7 /tmp/img.png
base64 -w 0 /tmp/img.png > `selection`
I want to put selection into the script and then get result of script execution and replace selected content with that result.
I see the workflow as selecting base64 part in visual block mode and type e.g. :'<,'>optipng or press some hotkey.
The question is how to setup vim to do that.

Vim allows to filter line(s) through an external command with :[range]!{cmd}. If your optipng command can take input from stdin and print to stdout, you can use it directly; else, with the help of a small shell script wrapper. See :help :range! for details.
One limitation is that this only works for whole lines, not parts, even when visually selected. You can get around this with the vis plugin; it would then be something like:
:'<,'>B !optipng -o7

Related

tmux pin to avoid scrolling

Often when I run a command that writes to stdout, and that command fails, I have to scroll up (using uncomfortable key-bindings) looking for the place where I pressed Enter, to see what the first error was (out of hundreds others, across many screens of text). This is both annoying and time-consuming. I wish there was a feature which allowed me to pin my current terminal to the place where I am now, then start the command, see only the first lines of the output (as many as fits below my cursor) and let the rest of the output be written but not displayed. In other words I would like a feature to allow me automatically scroll up to the place where I gave the command, to see the first lines of the output (where usually the origin of the failure is displayed).
I searched for it but I didn't find it. Do you know if such feature exists? Or have an idea how to implement it with some tricks or workarounds?
If you have a unique shell prompt you could bind a key to jump between shell prompts, for example something like this will make C-b S jump to the previous shell prompt then S subsequent ones:
bind S copy-mode \; send -X search-backward 'nicholas#myhost:'
bind -Tcopy-mode S send -X search-backward 'nicholas#myhost:'
Or similarly you could search for error strings if they have a recognisable prefix. If you install the tmux 3.1 release candidate, you can search for regular expressions.
Alternatively, you could use capture-pane to load the entire history into an editor with key bindings you prefer, for example:
$ tmux capturep -S- -E- -p|vim -
Or pipe to grep or whatever. Note you will need to use a temporary file for this to work with emacs.
Or try to get into the habit of teeing commands with lots of output to a file to start with.

Replace visual selection with command output

I would like to replace parts of one line with the result of the selection being piped into a command.
For example:
echo "hello $(echo "world" | base64)" | vim -
This will open a buffer with hello d29ybGQK in it. Now press wvw to visually select d29ybGQK.
Then I attempted :!base64 -d and I expected the buffer to contain hello world, which did not happen. Indeed, the whole line was piped into the command, and the whole line was replaced.
Is it possible to replace only the visual selection, and have only that selection piped into the command?
I also attempted c<c-r>=system('base64 -d') but that did not send the visual selection to the command's stdin.
Filtering with ! is always line-wise. Your solution with c and the
expression register is an excellent way to solve this. You only forgot
to pass the input to system(), which is its second optional argument.
Since you just changed the text selected, it went into the " register
automatically. All you need to do is to grab it back and pass it to
system with getreg():
c<C-R>=system('base64 -D', getreg('"'))
Note that base64 may echo a newline at the end. If you want to remove
it, either wrap the whole thing in trim(), a new function in Vim 8, or
use [:-2]:
c<C-R>=trim(system('base64 -D', getreg('"')))
c<C-R>=system('base64 -D', getreg('"'))[:-2]
This is a shorthand for [0:-2], meaning grab everything from character
0 to second-last in the resulting string.
Consider creating a visual map if you use it often:
vnoremap <leader>d c<C-R>=system('base64 -D', getreg('"'))[:-2]<CR>
For historical reasons, the Ex commands are inherently line-based; venerable vi also didn't have visual mode yet. That limitation includes filtering through an external command with :range!; it will always filter complete lines.
manual solution
For simple input like in your example, it's probably easiest to temporarily split the line, filter, and then reassemble. For example:
:substitute/ /\r/ | execute '.!base64 -d' | -1join
plugin solution
For a universal solution, you need to use or implement a plugin that grabs the selected text, filters it (probably through system()), and then replaces the selection with the result.
My SubstituteExpression plugin has a {Visual}g= mapping that can filter through Vimscript expressions, Vim functions and commands, and external commands.
express.vim by Tom McDonald offers an almost identical implementation. It also allows on-the-fly creation of operators via :MapExpress and :MapSubpress, something for which I would use my TextTransform plugin, which you need to install as a dependency, anyway. My plugin offers more advanced (cross-mode) repeats, and the :Ex-command expression variant, but has two large dependencies you also need to install.

substituting multiple possible patterns using OR in vim search

I often find myself using something like:
sed -ri 's/<\/(abc|def ghi|j klm)>//g' someFile.html
to perform substitutions on multiple possible patterns, in this case, a closing html tag to be deleted, saving me the time and effort to do this three separate times for three closing tags I want deleted.
Is there a way to do this using substitute on vim's cli? I haven't yet found a way to do it, but it would be more efficient than going to a terminal cli or running sed from within vim if it could be done natively instead.
Yes, you don't need to use an external program at all:
:%s#</\(foo\|bar\|baz\)>##g
You can use the silent ! command to silently execute shell commands from inside vim:
:silent !sed -ri 's/<\/(abc|def ghi|j klm)>//g' %
This will execute the command in the shell silently (it won't take you away from vim to see any shell output). The % means the current buffer name. Vim will then notify you that the file you are editing has been changed and will ask you if you want to load the changes, press l for load and the new changes from the sed shell command will appear.

How can I use vim in a pipeline to colorize text?

I'd like to have a command I can insert into a command pipeline that adds color escapes to its input according to vim's syntax highlighting capabilities.
For example:
cat somefile.js | vim - <???> | less
The resulting text would be that of somefile.js, but colorized according to how the current vim configuration would do it in-editor.
It occurs to me that this must be possible. I agree that the example up there isn't what a sane man might call exactly useful, but that doesn't mean the idea never is.
I think your idea has one basic flaw: that nobody ever thought about allowing such a thing.
Clearly vim is capable of doing syntax highlighting. But I'll bet you an ice cream cone that if you can manage to get vim to stream text through and process it, that you won't like the results.
Consider what happens when you pipe text through more (or less if you prefer). When it goes to the terminal, these programs display one screenful and wait for you to hit the space bar. But if you redirect stdout to some other place than the terminal, these programs notice this and simply copy their input to their output unchanged.
If vim doesn't notice that you are piping text through, it is likely to send cursor-movement commands that you probably don't want in your output. If vim does notice, it is likely to just pass the text, and not syntax-color it. Only if vim does do the syntax-coloring but does not inject cursor-movement stuff will your idea work.
You could try it. Here's an answer that discusses piping stuff through vim:
Execute a command within Vim from the command line
But I say why not pipe your text through a program that was designed and intended to have text piped through it? Pygments can colorize every major programming language and markup format.
http://pygments.org/
The major advantage I see for your idea: you can customize the way vim does syntax coloring, get it the way you want it, and then also use vim to process your text. But it's probably not that hard to customize Pygments, and it might even be satisfactory out of the box, in which case it would definitely be the easiest way to go. And Pygments not only has ANSI sequence output, it also has HTML output, RTF, LaTeX, etc. So if you get Pygments working the way you want it to, it should be able to output whatever output format you need; vim will only have the ANSI sequence one.
There's a Perl module called Text::VimColor that I've heard will do kinda what you're looking for.
http://search.cpan.org/dist/Text-VimColor/
But let me ask this: Why do want it to go through less? Why not use vim as a perfectly good file viewer? view - will read from standard input in read-only mode.
https://gist.github.com/echristopherson/4090959
Via https://superuser.com/a/554531/7198.
Tried on /etc/passwd and it works surprisingly well!
This might be what you're after
cat filename.sh | vim - -c 'syntax on; syn=bash'
This is ugly, but you could alias this:
alias vim.sh="vim -c 'syntax on; syn=bash'"
Then use like this:
cat filename.sh | vim.sh -
Use vimcat !
wget -O /usr/local/bin/vimcat "https://www.vim.org/scripts/download_script.php?src_id=23422"
chmod 755 /usr/local/bin/vimcat
vimcat /etc/passwd
See also: https://www.vim.org/scripts/script.php?script_id=4325

How do I insert a tab character in Iterm?

Simply put, I know you can do ctrl+v+tab to insert a physically real tab character in a bash statement. But how do I do the same for iTerm?
The answer was to hit control+v, then tab afterwards, not all together! Hope this helps someone.
It's not iTerm, but your shell that affects how you''re able to insert a tab.
First, make sure you're in BASH shell: Type the following command:
$ echo $RANDOM $BASH_VERSINFO
23714 3
The first is a random number, and the second should be the BASH Version number. If you get a blank line or just a random number, you're not in the BASH shell, and that's probably one of your issues.
Another thing is to execute this command:
$ set -o
allexport off
braceexpand on
emacs on
errexit off
errtrace off
[...]
privileged off
verbose off
vi off
trace off
The two lines of interest is the emacs and the vi lines. One of those should be on. If they're both off, you can't do the Ctrl-V-Tab to insert a tab character.
When the vi mode is on, it should be Ctrl-V-Tab like you said. With emacs mode on, it is either Ctrl-V-tab, or possibly Ctrl-Q-tab.
However, this isn't an iTerm thing, this is your shell that's doing it.
If by a "physically real tab character" you mean sending the tab hex code (0x09) to the shell, then you can do this in iTerm by pressing Ctrl + Tab (⌃ ⇥).
This is the default setting, although you can change it (as well as add other hex code values to send) in iTerm > Preferences > Profiles > Keys.
I'm not certain why you're comparing a "bash statement" with iTerm. You write bash scripts in iTerm. Which means, assuming you're writing your scripts in iTerm, you're already doing what you want.
I'll assume you mean scripting in vi vs command line. The way I get literal characters on the command line is by using vi editing mode. Do set -o vi. Then you can use ctrl+v followed by tab in the manner that you're used to.
IMO, using vi editing mode comes with a slew of other pluses like searching your history, faster navigation, etc. So you could just add it to your .bashrc if you wanted and use it all the time.
One should also try Ctl + V Ctl + I. It is working in konsole where Ctl+V+Tab deosn't work.

Resources