Enhancing TiddlyWiki: Rendering Programming Languages as Code Blocks

I would like to render an entire tiddler as a code block if its Type is a programming language (e.g. python, or text/x-python). Tiddly readily does this for CSS so it should be possible to apply it to other languages. Any ideas how? I would be interested in turning this feature into a plugin later on. This feature is ideal for storing small code, as I often do with Github Gist. But I prefer to use TiddlyWiki over Gist.

I’m open to using other plugins to achieve this, but I have found PrismJS for TiddlyWiki — a non-linear personal web notebook very useful since I can easily add highlighting for other languages.

By default, the TWCore cascade mechanism includes $:/config/ViewTemplateBodyFilters/code-body, which contains the following filter definition:

[field:code-body[yes]then[$:/core/ui/ViewTemplate/body/code]]

This means that if you add a field named code-body with a value of yes to a tiddler, that tiddler’s text field content will automatically be rendered using the $:/core/ui/ViewTemplate/body/code template, which is defined as:

<$codeblock code={{{ [<currentTiddler>get[text]] }}} language={{{ [<currentTiddler>get[type]else[text/vnd.tiddlywiki]] }}}/>

Note that the $codeblock widget also supports the language=... parameter, which in this case automatically applies the MIME type specified by the tiddler’s type field. Thus, if you install the TiddlyWiki “Highlight” plugin from the “Official TiddlyWiki Plugin Library” (see $:/ControlPanel > Plugins), and set your tiddler’s type field value to text/x-python, it will not only be displayed as a code block, but will also apply Python-specific highlighting to the code.

enjoy,
-e

6 Likes

Many things like this should be added to a context-menu or command-palette, so user can just search for it inside wiki.

1 Like

Wow, that was much easier than I thought. Thank you very much. I’m going to play with auto-setting those fields if the title ends with and extension (e.g. *.py) and see how that goes.

Based on this, I created a viewtoolbar button to use the highlight plug-in in the $:/core/ui/ViewTemplate/body/code - See this tiddler

Press this button to toggle the views - image

1 Like