| 1 |
===================== |
| 2 |
Use Pygments in Java |
| 3 |
===================== |
| 4 |
|
| 5 |
Thanks to `Jython <https://www.jython.org/>`_ it is possible to use Pygments in |
| 6 |
Java. |
| 7 |
|
| 8 |
This page is a simple tutorial to get an idea of how this works. You can |
| 9 |
then look at the `Jython documentation <https://jython.readthedocs.io/en/latest/>`_ for more |
| 10 |
advanced uses. |
| 11 |
|
| 12 |
Since version 1.5, Pygments is deployed on `Maven Central |
| 13 |
<https://repo1.maven.org/maven2/org/pygments/pygments/>`_ as a JAR, as is Jython |
| 14 |
which makes it a lot easier to create a Java project. |
| 15 |
|
| 16 |
Here is an example of a `Maven <https://maven.apache.org/>`_ ``pom.xml`` file for a |
| 17 |
project running Pygments: |
| 18 |
|
| 19 |
.. sourcecode:: xml |
| 20 |
|
| 21 |
<?xml version="1.0" encoding="UTF-8"?> |
| 22 |
|
| 23 |
<project xmlns="http://maven.apache.org/POM/4.0.0" |
| 24 |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 25 |
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 |
| 26 |
http://maven.apache.org/maven-v4_0_0.xsd"> |
| 27 |
<modelVersion>4.0.0</modelVersion> |
| 28 |
<groupId>example</groupId> |
| 29 |
<artifactId>example</artifactId> |
| 30 |
<version>1.0-SNAPSHOT</version> |
| 31 |
<dependencies> |
| 32 |
<dependency> |
| 33 |
<groupId>org.python</groupId> |
| 34 |
<artifactId>jython-standalone</artifactId> |
| 35 |
<version>2.5.3</version> |
| 36 |
</dependency> |
| 37 |
<dependency> |
| 38 |
<groupId>org.pygments</groupId> |
| 39 |
<artifactId>pygments</artifactId> |
| 40 |
<version>1.5</version> |
| 41 |
<scope>runtime</scope> |
| 42 |
</dependency> |
| 43 |
</dependencies> |
| 44 |
</project> |
| 45 |
|
| 46 |
The following Java example: |
| 47 |
|
| 48 |
.. sourcecode:: java |
| 49 |
|
| 50 |
PythonInterpreter interpreter = new PythonInterpreter(); |
| 51 |
|
| 52 |
// Set a variable with the content you want to work with |
| 53 |
interpreter.set("code", code); |
| 54 |
|
| 55 |
// Simple use Pygments as you would in Python |
| 56 |
interpreter.exec("from pygments import highlight\n" |
| 57 |
+ "from pygments.lexers import PythonLexer\n" |
| 58 |
+ "from pygments.formatters import HtmlFormatter\n" |
| 59 |
+ "\nresult = highlight(code, PythonLexer(), HtmlFormatter())"); |
| 60 |
|
| 61 |
// Get the result that has been set in a variable |
| 62 |
System.out.println(interpreter.get("result", String.class)); |
| 63 |
|
| 64 |
will print something like: |
| 65 |
|
| 66 |
.. sourcecode:: html |
| 67 |
|
| 68 |
<div class="highlight"> |
| 69 |
<pre><span class="k">print</span> <span class="s">"Hello World"</span></pre> |
| 70 |
</div> |