Published 2021-04-03.
Time to read: 1 minutes.
I frequently show HTML source code when I write. That HTML must be escaped prior to displaying it on a web page.
Script to Apply HTML Escape to Clipboard
This bash script applies an HTML escape conversion to the contents of the system clipboard.
If you have WSL on your machine, you could store it on the WSL file system, for example in
~/.local/bin/escapeHtml
.
#!/bin/bash # SPDX-License-Identifier: Apache-2.0 function help { echo "$(basename $0) - Escapes HTML with entities. Reads from STDIN or pipe, or converts the clipboard. Result is copied to the clipboard. " exit 1 } function filesAreLinked { "$1" -ef "$2" } function checkDependencies { if [ -z `which recode` ]; then yes | sudo apt install recode; fi # See https://github.com/sindresorhus/clipboard-cli if [ -z `which clipboard` ]; then if [ "$( filesAreLinked /bin/npm /usr/local/lib/node_modules/npm/bin/npm-cli.js )" ]; then # No nodejs venv sudo -H npm install --global clipboard-cli else # nodejs venv npm install --global clipboard-cli fi fi } if [ "$1" == -h ]; then help; fi checkDependencies if [ -t 0 ]; then # Not reading from a terminal HTML="$( clipboard )" else # Reading from stdin or pipe # See https://stackoverflow.com/a/32365596/553865 HTML=$(cat; echo x) HTML=${HTML%x} # Strip the trailing x fi RESULT="$( recode utf8..html <<< "$HTML" )" echo "$RESULT" | sed "s/ //g" | sed "s/'/\'/g" | clipboard echo "$( echo "$RESULT" | wc -l ) lines have been placed on the clipboard."
Using the Script
- Select some text in any document or anywhere that text can be selected.
- Run
escapeHtml
on the same machine. If you have Windows with WSL you can run the script there, or run it in native Windows, does not matter. - Paste escaped HTML into your target document.
Hot Key Trigger
Trigger the script with a hot key via your OS's facilities. This section just discusses how native Windows hot keys can be used to trigger this script running in WSL.
- Right-click in a folder
- Select New / Shortcut
-
For Type the location of the item, type:
Type the location of the item%windir%\System32\wsl.exe ~/.local/bin/escapeHtml/escapeHtml
- Click Change icon and select a retro icon for this shortcut.
- Click on Apply.
- Click on Next.
-
When prompted for Type a name for this shortcut,
save as
HTML Escape Clip to Clip
. - Click on Finish.
- Right-click on the new shortcut and click in Shortcut key
- I used CTRL+ALT+A.
- Click on OK.
You can now quickly copy HTML from any source to the clipboard, apply an HTML escape conversion to the clipboard contents, and then paste the escaped HTML into an editor.