How to highlight the syntax for any languages and script like html, xml, python, C, C++, Java, groovy etc in a super easy way using Syntax Highlighter (by Alex Gorbatchev). Though this library is available for quite a long time but there are still doubts and difficulty faced by new programmer. This guide will help you get your code working in perfect 5 mins or less !!
This article consists of complete working code, with steps to for syntax highlighting and publishing of code in website, blog or html.
Below are the end to end steps for using Syntax highlighter.
Note: Brush files are language/script specific, so use only really required brush files in your html page instead of including of all languages. Also, you can download the sample code of this article(Link in last section) where you will find all required css and js as listed below
- Include command for applying syntaxhighlighter to all the pre tag with Brushes as shown in code below between line number 67-70
- Include the code to be displayed in page inside pre tag as shown in below code
- HTML example: Line number: 16
- Java example: Line number: 42
- Python example: Line number: 53
- Important :It is always better idea to escape following characters while displaying html inside your page:
- " to replaced with "
- & to replaced with &
- < to replaced with <
- > to replaced with >
The easiest way to do so is an online tool for escaping and de-escaping html: freeformatter.com
If you have followed above mentioned 5 steps, then the below code in Section.4 Working sample code will render following UI.
Below is the Working sample code:
Few points to be noted
- Escaping and descaping is essential matra for html display.
- One can customize the line number display by using attribute in pre class: <pre class="brush: js; html-script: true; first-line: -3; highlight: [1,12]">.
Similarly for highlighting particular lines, provide the list of line number as follow: <pre class="brush: js; html-script: true; first-line: -3; highlight: [1, 2, 3, 9,12]">
- Once you have included the brush file for any language or script, remember to use that in pre tag's class
Here is a quick video about how to install and start using Syntax Highlighter
If you have followed this tutorial so far and able to highlight code using syntaxhighlighter, you must have noted the presence of green colored toolbar icon on top-right corner. Clicking which takes us to Credit pop-up dialog box for SyntaxHighlighter
Due to several reasons, one would wish to remove the green toolbar icon from syntaxhighlighter division. It is possible to do in following ways
CSS MethodIn file 'shThemeDefault.css' add property for
display: none;inside, selector:
'.syntaxhighlighter .toolbar '
<body>tag, alongwith statement
SyntaxHighlighter.all();include this statement
SyntaxHighlighter.defaults.toolbar = false;or
SyntaxHighlighter.defaults['toolbar'] = false;
About the author
You can contact him at firstname.lastname@example.org