Sometimes it’s useful to copy some code from a file and paste it somewhere else as an example. For instance, I like to write code in a jsfiddle and then paste a relevant subset of that code to a Stack Overflow answer. I have also copied code from a project file to paste into HipChat to quickly explain something to a coworker, or to paste into a JIRA ticket as a comment.
If you copy code from the middle of a file, there’s usually some leading whitespace on all lines
that you do not want to preserve in the context into which you are pasting the code. The problem is
that you don’t want to get rid of all leading whitespace on all lines; you want to keep the
indentation intact. I usually get rid of the unwanted whitespace by manually deleting it
if it’s only one or two lines or by pasting into a new
vim buffer and using
<< to shift the text
over as much as desired.
To illustrate, I have this text:
1 2 3 4 5 6 7
and I want this text:
1 2 3 4 5 6 7
Remove leading whitespace
I knew there must be a way to remove the shortest leading whitespace from all lines
programmatically, but I’m not familiar enough with
sed, or shell scripting in general to
tackle the problem. I asked the question on Stack Overflow and got a few great answers. I
ended up accepting the single process
If you use OS X, the built-in
awk will not work with the given solution. If you use
Hombrew, fixing that is just a simple matter of
brew install gawk and using
The given solution has a great explanation and works fine, but I made one addition. If the input is
a single line with no leading whitespace, the script fails. I fixed this with
if (!s) s=0; at
the beginning of the
The final version of my command looks like this. I’ve added some comments to explain what’s going on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
It is worth noting that this probably only works on text with spaces for whitespace, not tabs or mixed whitespace.
Integrate with an Alfred workflow
The ability to remove the shortest leading whitespace with a shell command is great, but I really wanted a way to do this quickly with text on the clipboard. Alfred workflows make that possible.
I created a simple three step workflow with a hotkey trigger, a script action, and a clipboard output. You can download it here and use it with Alfred 2.
And now you can copy code in context and paste it with no leading whitespace wherever you want!