| 1 |
===================== |
| 2 |
Unicode and Encodings |
| 3 |
===================== |
| 4 |
|
| 5 |
Since Pygments 0.6, all lexers use unicode strings internally. Because of that |
| 6 |
you might encounter the occasional :exc:`UnicodeDecodeError` if you pass strings |
| 7 |
with the wrong encoding. |
| 8 |
|
| 9 |
Per default all lexers have their input encoding set to `guess`. This means |
| 10 |
that the following encodings are tried: |
| 11 |
|
| 12 |
* UTF-8 (including BOM handling) |
| 13 |
* The locale encoding (i.e. the result of `locale.getpreferredencoding()`) |
| 14 |
* As a last resort, `latin1` |
| 15 |
|
| 16 |
If you pass a lexer a byte string object (not unicode), it tries to decode the |
| 17 |
data using this encoding. |
| 18 |
|
| 19 |
You can override the encoding using the `encoding` or `inencoding` lexer |
| 20 |
options. If you have the `chardet`_ library installed and set the encoding to |
| 21 |
``chardet`` if will analyse the text and use the encoding it thinks is the |
| 22 |
right one automatically: |
| 23 |
|
| 24 |
.. sourcecode:: python |
| 25 |
|
| 26 |
from pygments.lexers import PythonLexer |
| 27 |
lexer = PythonLexer(encoding='chardet') |
| 28 |
|
| 29 |
The best way is to pass Pygments unicode objects. In that case you can't get |
| 30 |
unexpected output. |
| 31 |
|
| 32 |
The formatters now send Unicode objects to the stream if you don't set the |
| 33 |
output encoding. You can do so by passing the formatters an `encoding` option: |
| 34 |
|
| 35 |
.. sourcecode:: python |
| 36 |
|
| 37 |
from pygments.formatters import HtmlFormatter |
| 38 |
f = HtmlFormatter(encoding='utf-8') |
| 39 |
|
| 40 |
**You will have to set this option if you have non-ASCII characters in the |
| 41 |
source and the output stream does not accept Unicode written to it!** |
| 42 |
This is the case for all regular files and for terminals. |
| 43 |
|
| 44 |
Note: The Terminal formatter tries to be smart: if its output stream has an |
| 45 |
`encoding` attribute, and you haven't set the option, it will encode any |
| 46 |
Unicode string with this encoding before writing it. This is the case for |
| 47 |
`sys.stdout`, for example. The other formatters don't have that behavior. |
| 48 |
|
| 49 |
Another note: If you call Pygments via the command line (`pygmentize`), |
| 50 |
encoding is handled differently, see :doc:`the command line docs <cmdline>`. |
| 51 |
|
| 52 |
.. versionadded:: 0.7 |
| 53 |
The formatters now also accept an `outencoding` option which will override |
| 54 |
the `encoding` option if given. This makes it possible to use a single |
| 55 |
options dict with lexers and formatters, and still have different input and |
| 56 |
output encodings. |
| 57 |
|
| 58 |
.. _chardet: https://chardet.github.io/ |