Vim does OCR for me
Harness the Power of External Commands in Vim
There are tons of powerful command line tools available. Vim's ex-command :! opens the horizon to access these external programs. For example we can list current directory contents from Vim using :!ls command.
Let’s see some of the external commands in action.
Open Current File in Default Program
After editing an HTML file (or any file) I can simply open it in web browser (i.e., default program) using !open %.
Note that open is a symlink to xdg-open in Debian systems.
Read Output of External Command
Vim also allows to read the output of external command into current buffer. It can be done using :read! or :r! in short.
Sometimes to create random unique IDs, I use Linux utility command named uuidgen and read its output using r!uuidgen.
Pass Input to External Command and Replace
The bang (exclamation) ex-command also takes a range, e.g., :1,3!<cmd>. Here the contents from line one to three are passed as input to the <cmd> and the output replaces those line one to three. This feature comes very handy while formatting a codeblock.
Lets say you have ugly JSON string:
[{"name":"John Doe", "age":35},{"name":"Jane Doe", "age":30}]You can visually select the string and pass it to jq using '<,'>!jq command. It gets formatted:
[
{
"name": "John Doe",
"age": 35
},
{
"name": "Jane Doe",
"age": 30
}
]Similarly you can get HTML boilerplate or format HTML code by passing it into pup.
Okay I can hear you screaming, “Its all nice, but where is the OCR?“ So let’s talk about it.
OCR in Vim!
Although the heading is cheesy, the fact of the matter is that all the shell scripts in $PATH can be invoked similarly.
Taking advantage of the powerful tool tesseract, one can write a bash script to do OCR (Optical Character Recognition) on clipboard image and return the text. Then simply read the text in Vim buffer using :r!ocr. Voila!
Conclusion
The specific program used here is not important. What important is the powerful idea that all command line programs are available within Vim. Just pick and choose as per your need.
I hope it adds some value to your Vimmy journey. Do share other useful external commands you like to use. Any feedback regarding the the content or the bash script is highly appreciated.


