pygments-main / docs / src / java.txt

Full commit
Use Pygments in Java

Thanks to `Jython <>`__ it is possible to use Pygments in

This page is a simple tutorial to get an idea of how this is working. You can
then look at the `Jython documentation <>`__ for more
advanced use.

Since version 1.5, Pygments is deployed on `Maven Central
<>`__ as a JAR so is Jython
which makes it a lot easier to create the Java project.

Here is an example of a `Maven <>`__ ``pom.xml`` file for a
project running Pygments:

.. sourcecode:: xml

    <?xml version="1.0" encoding="UTF-8"?>

    <project xmlns=""

The following Java example:

.. sourcecode:: java

    PythonInterpreter interpreter = new PythonInterpreter();

    // Set a variable with the content you want to work with
    interpreter.set("code", code);

    // Simple use Pygments as you would in Python
    interpreter.exec("from pygments import highlight\n"
        + "from pygments.lexers import PythonLexer\n"
        + "from pygments.formatters import HtmlFormatter\n"
        + "\nresult = highlight(code, PythonLexer(), HtmlFormatter())");

    // Get the result that has been set in a variable
    System.out.println(interpreter.get("result", String.class));

will print something like:

.. sourcecode:: html

    <div class="highlight">
    <pre><span class="k">print</span> <span class="s">&quot;Hello World&quot;</span></pre>