Function Repository Resource:

SyntaxHighlight

Source Notebook

Syntax-highlight a code string

Contributed by: Wolfram Staff

ResourceFunction["SyntaxHighlight"][code,lang]

gives the string for code with syntax highlighting corresponding to the language lang.

Details and Options

ResourceFunction["SyntaxHighlight"][string,] passes the code string to the Python package Pygments for processing in an external session.
ResourceFunction["SyntaxHighlight"] requires Python, which can be installed with SystemInstall["Python"].
The produced syntax highlighting is only as good as the corresponding lexer used by the Pygments package.

Examples

Basic Examples (4) 

Generate a syntax-highlighted version of a Python package:

In[1]:=
ResourceFunction["SyntaxHighlight"][
 Import[FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "Databases", "Python", "wolfram", "execution", "evaluate.py"}], "Text"], "Python"]
Out[1]=

Highlight a snippet of C code:

In[2]:=
ResourceFunction["SyntaxHighlight"][
 Import[FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "LibraryLink", "LibraryResources", "Source", "arbitraryTensor.c"}], "Text"], "C"]
Out[2]=

Highlight a snippet of Java code:

In[3]:=
ResourceFunction["SyntaxHighlight"][
 Import[FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "DatabaseLink", "Java", "com", "wolfram", "databaselink", "examples", "Command.java"}], "Text"], "C"]
Out[3]=

Highlight a snippet of code from a Wolfram Language package:

In[4]:=
ResourceFunction["SyntaxHighlight"][
 Import[FindFile["Blockchain`Wolfram`"], "Text"], "WolframLanguage"]
Out[4]=

Possible Issues (2) 

SyntaxHighlight fails if the Pygments Python package is not installed:

In[5]:=
ResourceFunction["PythonPackageInstalledQ"]["Pygments"]
Out[5]=
In[6]:=
ResourceFunction["SyntaxHighlight"]["2+2", "WolframLanguage"]
Out[6]=

Run the same command after installing Pygments:

In[7]:=
ResourceFunction["PythonPackageInstall"]["Pygments"]
Out[7]=
In[8]:=
ResourceFunction["SyntaxHighlight"]["2+2", "WolframLanguage"]
Out[8]=

Version History

  • 1.0.0 – 12 August 2019

Related Resources

License Information