insert bash script output in vim file

Viewed 93

I'm writing markdown in Vim and using this shortcut to set correct markdown image syntax:

nnoremap <leader>p :s/.*/![](\0)/ <CR>

when pressing ,p, /path/to/image/img.jpg (in my vim text file) becomes

![](/path/to/image/img.jpg)

But I want to add after that this { width = *variable*% }, like this

![](img.jpg){ width = *variable*% }

I made this little bash script (img.sh) that gives me the variable according to the image size:

#!/bin/bash

VAR=$(identify -format '%h' $1)

echo "scale=3; 300 * (100/$VAR)" | bc

If I do this in vim :r !img.sh /path/to/image/img.jpg I get a number in this case 32

I would want to launch this script with the shortcut above, I tried this:

nnoremap <leader>p :s/.*/![](\0){ width=/ <CR> :r !img.sh /path/to/image/img.jpg <CR> % }

I want you to help me to find a way to not type path to image to execute the script. Path to image is already written in the text if i could find a way to indicate to vim to place it in the shortcut after img.sh it would be great !

1 Answers

You can use a Vimscript expression on the replacement side of your :s command, that way you can refer to the text in the match (which is the path to the image) using submatch(0). You can use an expression on the replacement of a :s by beginning it with \=, see :help sub-replace-expression for more details.

Using a replacement expression, you can also use the system() function to call the external command, instead of using a separate :r !... command to read its output into the current buffer.

Putting it all together:

:s/.*/\='![]('.submatch(0).']{ width='.trim(system('img.sh '.submatch(0))).' }'/

Or to add a mapping to it:

nnoremap <leader>p :s/.*/\='![]('.submatch(0).']{ width='.trim(system('img.sh '.submatch(0))).' }'/<CR>

(NOTE: You might also want to add a :noh command to the end of your mapping, otherwise it will keep highlighting the search for .* which matches everything.)

nnoremap <leader>p :s/.*/\='![]('.submatch(0).']{ width='.trim(system('img.sh '.submatch(0))).' }'/\|noh<CR>
Related