Easy text selection into a code block using a hotkey (Templater)

Mostly for CSS, but I found myself wanting to quickly create a fenced code block from selected text without typing ``` and then the code language over and over again. I’ve been using a few different versions for months now without issue. Hopefully, a few of you will find it useful!


  • Install the Templater community plugin.

  • Paste the below code into a new note, give it a template sounding name that works for you, and move it to your Templater templates folder.

  • Set a “Template Hotkey” for this template in Templater’s settings.

  • Assign/configure the hotkey. I use Cmd + Optn + C, but it can be anything as long as the hotkey isn’t already assigned.

The template:

//get selection
noteContent = tp.file.selection();
//get array of lines
lines = noteContent.split('\n')
let newContent = "";
lines.forEach(l => {
    newContent += '' + l + "\n";
newContent = newContent.replace(/\n$/, "");
//assign the code block language - change {css} to {html}, {php}, etc.
header = "```css"+ "\n"
//place cursor after last selected character and add final backticks 
return header + newContent + "\<% tp.file.cursor() %\>" + "\n" + "```";


If there’s no text selected and you run the template / use the hotkey, you’ll get this:

<cursor here>

CleanShot 2024-04-09 at 10.03.48

If there’s text selected and you run the template / use the hotkey, everything will be neatly wrapped up in a code block:

CleanShot 2024-04-09 at 10.08.38

Special thanks to Zachatoo for the assist in getting the final cursor location sorted out.

It shouldn’t eat your CSS, any other code, or text, but it is provided as is. Enjoy! :cherry_blossom: