Mike Slinn
Mike Slinn

Escaping HTML on Clipboard From a Windows Hot Key via WSL

Published 2021-04-03.
Time to read: about 2 minutes.

This article is categorized under WSL.

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 /usr/local/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

  1. Select some text in any document or anywhere that text can be selected.
  2. 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.
  3. 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.

  1. Right-click in a folder
  2. Select New / Shortcut
  3. For Type the location of the item, type:

    Type the location of the item
    %windir%\System32\wsl.exe ~/.local/bin/escapeHtml/escapeHtml
  4. Click Change icon and select a retro icon for this shortcut.
  5. Click on Apply.
  6. Click on Next.
  7. When prompted for Type a name for this shortcut, save as HTML Escape Clip to Clip.
  8. Click on Finish.
  9. Right-click on the new shortcut and click in Shortcut key
  10. I used Ctrl+Alt+A.
  11. 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.

😁