How to Add GDScript Syntax Highlighting to Your Blog

Recently, I decided to devote more time to writing blog posts, especially tutorials about things I’ve learned in my three-plus years of learning Godot and GDScript. When I went to write my first tutorial post, however, I discovered that there is no support for GDScript syntax highlighting in any of the code formatting plugins for WordPress. On top of that, Github’s Gists, which I’ve used to show syntax-highlighted code in the past, also does not support GDScript.

Syntax highlighting, for those who don’t know, is the colorful text and different font weights and decorations (aka bolded, italicized, and underlined text) that code editors show to indicate different functionalities of code. Using syntax highlighting to show what your code is doing is extremely helpful, if not critically important for making your code readable. Without syntax highlighting, it’s a lot more difficult to parse what a given block of code is doing, to the point where it feels unreadable. For tutorials, it’s especially important to make code as easy to understand as possible, and a critical part of that is including syntax highlighting.

Imagine trying to read a blog article where all the code samples were one giant block of monochromatic text, like this:

It’s a little tricky, isn’t it? Maybe you can read this particular example after a few moments, but what about 20-50 line examples of complex code? And what if you’re scanning back and forth between code samples, trying to parse how the whole thing works? It was clear to me that, if I wanted to write tutorials that were user-friendly, I needed to find a way to add support for GDScript syntax highlighting to my website.

After asking in the Godot Discord, I was pointed towards an implementation of GDScript in highlight.js, a JavaScript-based syntax highlighter. Some additional googling showed me how I could integrate highlight.js onto a website, and further research showed how to make changes to a WordPress website’s head file. Combining this information together, I was able to successfully integrate highlight.js and the GDscript extension for it onto my blog.

First, I went to Appearance -> Theme Editor and edited the header.php file, adding this snippet right below the wp_head() function call, to take care of downloading highlight.js:

<!-- Syntax highlighting for code blocks. -->
<link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/highlight.min.js"></script>

Next, I went to the Github repo for hilightjs-gdscript and copied the contents of the gdscript.min.js file, adding it just below where I added the main highlight.js script tag:

<!-- Syntax highlighting for GDScript. -->
<script>hljs.registerLanguage("gdscript",function(){"use strict";var e=e||{};function r(e){return{aliases:["godot","gdscript"],keywords:{keyword:"and in not or self void as assert breakpoint class class_name extends is func setget signal tool yield const enum export onready static var break continue if elif else for pass return match while remote sync master puppet remotesync mastersync puppetsync",built_in:"Color8 ColorN abs acos asin atan atan2 bytes2var cartesian2polar ceil char clamp convert cos cosh db2linear decimals dectime deg2rad dict2inst ease exp floor fmod fposmod funcref get_stack hash inst2dict instance_from_id inverse_lerp is_equal_approx is_inf is_instance_valid is_nan is_zero_approx len lerp lerp_angle linear2db load log max min move_toward nearest_po2 ord parse_json polar2cartesian posmod pow preload print_stack push_error push_warning rad2deg rand_range rand_seed randf randi randomize range_lerp round seed sign sin sinh smoothstep sqrt step_decimals stepify str str2var tan tanh to_json type_exists typeof validate_json var2bytes var2str weakref wrapf wrapi bool int float String NodePath Vector2 Rect2 Transform2D Vector3 Rect3 Plane Quat Basis Transform Color RID Object NodePath Dictionary Array PoolByteArray PoolIntArray PoolRealArray PoolStringArray PoolVector2Array PoolVector3Array PoolColorArray",literal:"true false null"},contains:[e.NUMBER_MODE,e.HASH_COMMENT_MODE,{className:"comment",begin:/"""/,end:/"""/},e.QUOTE_STRING_MODE,{variants:[{className:"function",beginKeywords:"func"},{className:"class",beginKeywords:"class"}],end:/:/,contains:[e.UNDERSCORE_TITLE_MODE]}]}}return e.exports=function(e){e.registerLanguage("gdscript",r)},e.exports.definer=r,e.exports.definer||e.exports}());</script>

Imagine trying to read the above without syntax highlighting!

Finally, I added a call to initiate highlight.js, right below the highlightjs-gdscript code:

<script>hljs.highlightAll();</script>

And with that (omitting some trial and error on my part to figure out the above), I successfully got highlight.js to run on my WordPress blog, with syntax highlighting for GDscript!

I wasn’t happy with the out-of-the-box highlighting, though, so I decided to quickly throw together some custom styles, targeting the classes highlight.js injects. First, I went to Appearance -> Edit CSS in the WordPress menu settings and injected this CSS styling:

:root {
    --code-background: #000004;
    --default-font-color: #fbfef9;
    --keyword-color: #7e1946;
    --title-color: #a63446;
    --function-color: #0c6291;
    --string-color: #6ea735;
    --html-color: #a76e35;
}

code {
	border: none;
	padding: 0;
	font-size: 0.9em;
}

pre, code, code.hljs {
    background: var(--code-background);
    color: var(--default-font-color);
}

code.hljs .hljs-function,
code.hljs .hljs-function .hljs-keyword {
    color: var(--function-color);
}

code.hljs .hljs-keyword {
    color: var(--keyword-color);
}

code.hljs .hljs-title {
    color: var(--title-color);
}

code.hljs .hljs-string {
    color: var(--string-color);
}

code.hljs .hljs-name,
code.hljs .hljs-tag,
code.hljs .hljs-attr {
    color: var(--html-color);
}

I also made changes to other parts of the highlight.js syntax highlighting that weren’t for GDScript to make them work with my new color scheme.

I also noticed that highlight.js wasn’t consistently auto-detecting when I was using GDScript, so I converted my WordPress code block to an HTML block and created the code tags manually:

<pre class="wp-block-code"><code class="language-gdscript"></code></pre>

Finally, highlightjs-gdscript didn’t include support for print, so I quickly added that to my import of the dist file:

{ keyword:"and in not or self void as assert breakpoint class class_name extends is func setget signal tool yield const enum export onready static var break continue if elif else for pass return match while remote sync master puppet remotesync mastersync puppetsync print" }

The final result looks like this:

At least, that’s what it looked like at the time I wrote this blog post. Since I was just looking to throw something together quickly, I didn’t put too much thought into my color scheme, instead utilizing a randomly-generated color palette (https://coolors.co/a63446-fbfef9-0c6291-000004-7e1946) and some hue-shifting to get related colors that weren’t part of the generated palette. Below is what the syntax highlight looks like on today’s iteration of the color scheme:

func ready():
  var variable = some_function()
  print("Hopefully this syntax highlighting works!")

Anyway, that’s a quick overview on how I implemented GDScript syntax highlighting on a WordPress blog. I imagine much of this can be adapted to implement GDScript syntax highlighting on any site. Now, on to writing blog posts!

2 Comments

  • Johan

    2022-09-14 at 3:27 pm Reply

    Thanks. I found this helpful.

    Of course, I immediately dived into creating an extension for Highlight.js, but even the un-minimized code is hard for me to read. So leaving it alone for now. Would be nice to do it though.

    I ended up downloading my own version of highlighter, where I disabled PHP and others. So now at least it correctly recognises GDScript blocks.

Post a Comment