| 1 | # Ansimarkup |
| 2 | |
| 3 | <p> |
| 4 | <a href="https://pypi.python.org/pypi/ansimarkup"><img alt="pypi version" src="https://img.shields.io/pypi/v/ansimarkup.svg"></a> |
| 5 | <a href="https://github.com/gvalkov/python-ansimarkup/actions/workflows/tests.yml?query=branch:main"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/gvalkov/python-ansimarkup/tests.yml?branch=main"></a> |
| 6 | <a href="https://github.com/gvalkov/python-ansimarkup/blob/main/LICENSE.txt"><img alt="License" src="https://img.shields.io/pypi/l/ansimarkup"></a> |
| 7 | </p> |
| 8 | |
| 9 | Ansimarkup is an XML-like markup for producing colored terminal text. |
| 10 | |
| 11 | ``` python |
| 12 | from ansimarkup import ansiprint as print |
| 13 | |
| 14 | print("<b>bold text</b>")) |
| 15 | print("<red>red text</red>", "<red,green>red text on a green background</red,green>") |
| 16 | print("<fg #ffaf00>orange text</fg #ffaf00>") |
| 17 | ``` |
| 18 | |
| 19 | ## Installation |
| 20 | |
| 21 | The latest stable version of ansimarkup can be installed from PyPi: |
| 22 | |
| 23 | ``` bash |
| 24 | python3 -m pip install ansimarkup |
| 25 | ``` |
| 26 | |
| 27 | ## Usage |
| 28 | |
| 29 | ### Basic |
| 30 | |
| 31 | ``` python |
| 32 | from ansimarkup import parse, ansiprint |
| 33 | |
| 34 | # parse() converts the tags to the corresponding ansi escape sequence. |
| 35 | parse("<b>bold</b> <d>dim</d>") |
| 36 | |
| 37 | # ansiprint() works exactly like print(), but first runs parse() on all arguments. |
| 38 | ansiprint("<b>bold</b>", "<d>dim</d>") |
| 39 | ansiprint("<b>bold</b>", "<d>dim</d>", sep=":", file=sys.stderr) |
| 40 | ``` |
| 41 | |
| 42 | ### Colors and styles |
| 43 | |
| 44 | ``` python |
| 45 | # Colors may be specified in one of several ways. |
| 46 | parse("<red>red foreground</red>") |
| 47 | parse("<RED>red background</RED>") |
| 48 | parse("<fg red>red foreground</fg red>") |
| 49 | parse("<bg red>red background</bg red>") |
| 50 | |
| 51 | # Xterm, hex and rgb colors are accepted by the <fg> and <bg> tags. |
| 52 | parse("<fg 86>aquamarine foreground</fg 86>") |
| 53 | parse("<bg #00005f>dark blue background</bg #00005f>") |
| 54 | parse("<fg 0,95,0>dark green foreground</fg 0,95,0>") |
| 55 | |
| 56 | # Tags may be nested. |
| 57 | parse("<r><Y>red text on a yellow foreground</Y></r>") |
| 58 | |
| 59 | # The above may be more concisely written as: |
| 60 | parse("<r,y>red text on a yellow background</r,y>") |
| 61 | |
| 62 | # This shorthand also supports style tags. |
| 63 | parse("<b,r,y>bold red text on a yellow background</b,r,y>") |
| 64 | parse("<b,r,>bold red text</b,r,>") |
| 65 | parse("<b,,y>bold regular text on a yellow background</b,,y>") |
| 66 | |
| 67 | # Unrecognized tags are left as-is. |
| 68 | parse("<b><element1></element1></b>") |
| 69 | ``` |
| 70 | |
| 71 | For a list of markup tags, please refer to [tags.py]. |
| 72 | |
| 73 | ### User-defined tags |
| 74 | |
| 75 | Custom tags or overrides for existing tags may be defined by creating a |
| 76 | new `AnsiMarkup` instance: |
| 77 | |
| 78 | ``` python |
| 79 | from ansimarkup import AnsiMarkup, parse |
| 80 | |
| 81 | user_tags = { |
| 82 | # Add a new tag (e.g. we want <info> to expand to "<bold><green>"). |
| 83 | "info": parse("<b><g>") |
| 84 | |
| 85 | # The ansi escape sequence can be used directly. |
| 86 | "info": "e\x1b[32m\x1b[1m", |
| 87 | |
| 88 | # Tag names may also be callables. |
| 89 | "err": lambda: parse("<r>") |
| 90 | |
| 91 | # Colors may also be given convenient tag names. |
| 92 | "orange": parse("<fg #d78700>"), |
| 93 | |
| 94 | # User-defined tags always take precedence over existing tags. |
| 95 | "bold": parse("<dim>") |
| 96 | } |
| 97 | |
| 98 | am = AnsiMarkup(tags=user_tags) |
| 99 | |
| 100 | am.parse("<info>bold green</info>") |
| 101 | am.ansiprint("<err>red</err>") |
| 102 | |
| 103 | # Calling the instance is equivalent to calling its parse method. |
| 104 | am("<b>bold</b>") == am.parse("<b>bold</b>") |
| 105 | ``` |
| 106 | |
| 107 | ### Alignment and length |
| 108 | |
| 109 | Aligning formatted strings can be challenging because the length of the |
| 110 | rendered string is different that the number of printable characters. |
| 111 | Consider this example: |
| 112 | |
| 113 | ``` pycon |
| 114 | >>> a = '| {:30} |'.format('abc') |
| 115 | >>> b = '| {:30} |'.format(parse('<b>abc</b>')) |
| 116 | >>> print(a, b, sep='\n') |
| 117 | | abc | |
| 118 | | abc | |
| 119 | ``` |
| 120 | |
| 121 | This can be addressed by using the `ansistring` function or the |
| 122 | `AnsiMarkup.string(markup)` method, which has the following useful |
| 123 | properties: |
| 124 | |
| 125 | ``` pycon |
| 126 | >>> s = ansistring('<b>abc</b>') |
| 127 | >>> print(repr(s), '->', s) |
| 128 | <b>abc</b> -> abc # abc is printed in bold |
| 129 | >>> len(s), len(am.parse('<b>abc</b>'), s.delta |
| 130 | 3, 11, 8 |
| 131 | ``` |
| 132 | |
| 133 | With the help of the `delta` property, it is easy to align the strings |
| 134 | in the above example: |
| 135 | |
| 136 | ``` pycon |
| 137 | >>> s = ansistring('<b>abc</b>') |
| 138 | >>> a = '| {:{width}} |'.format('abc', width=30) |
| 139 | >>> b = '| {:{width}} |'.format(s, width=(30 + s.delta)) |
| 140 | >>> print(a, b, sep='\n') |
| 141 | | abc | |
| 142 | | abc | |
| 143 | ``` |
| 144 | |
| 145 | ### Escaping raw strings |
| 146 | |
| 147 | Both `ansiprint()` and `parse()` pass arguments of type `raw` untouched. |
| 148 | |
| 149 | ``` pycon |
| 150 | >>> from ansimarkup import ansiprint, parse, raw |
| 151 | >>> ansiprint("<b><r>", raw("<l type='V'>2.0</l>"), "</r></b>") |
| 152 | <l type='V'>2.0</l> # printed in bold red (note the leading space caused) |
| 153 | |
| 154 | >>> s = parse("<b><r>", raw("<l type='V'>2.0</l>"), "</r></b>") |
| 155 | >>> print(s) |
| 156 | <l type='V'>2.0</l> # printed in bold red |
| 157 | ``` |
| 158 | |
| 159 | Building a template string may also be sufficient: |
| 160 | |
| 161 | ``` pycon |
| 162 | >>> from ansimarkup import parse |
| 163 | >>> s = parse("<b><r>%s</r></b>") |
| 164 | >>> print(s % "<l type='V'>2.0</l>") |
| 165 | <l type='V'>2.0</l> # printed in bold red |
| 166 | ``` |
| 167 | |
| 168 | |
| 169 | ### Other features |
| 170 | |
| 171 | The default tag separators can be changed by passing the `tag_sep` |
| 172 | argument to `AnsiMarkup`: |
| 173 | |
| 174 | ``` python |
| 175 | from ansimarkup import AnsiMarkup |
| 176 | |
| 177 | am = AnsiMarkup(tag_sep="{}") |
| 178 | am.parse("{b}{r}bold red{/b}{/r}") |
| 179 | ``` |
| 180 | |
| 181 | Markup tags can be removed using the `strip()` method: |
| 182 | |
| 183 | ``` python |
| 184 | from ansimarkup import AnsiMarkup |
| 185 | |
| 186 | am = AnsiMarkup() |
| 187 | am.strip("<b><r>bold red</b></r>") |
| 188 | ``` |
| 189 | |
| 190 | The `strict` option instructs the parser to raise `MismatchedTag` if |
| 191 | opening tags don\'t have corresponding closing tags: |
| 192 | |
| 193 | ``` python |
| 194 | from ansimarkup import AnsiMarkup |
| 195 | |
| 196 | am = AnsiMarkup(strict=True) |
| 197 | am.parse("<r><b>bold red") |
| 198 | # ansimarkup.MismatchedTag: opening tag "<r>" has no corresponding closing tag |
| 199 | ``` |
| 200 | |
| 201 | ### Command-line |
| 202 | |
| 203 | Ansimarkup may also be used on the command-line. This works as if all |
| 204 | arguments were passed to `ansiprint()`: |
| 205 | |
| 206 | $ python -m ansimarkup |
| 207 | Usage: python -m ansimarkup [<arg> [<arg> ...]] |
| 208 | |
| 209 | Example usage: |
| 210 | python -m ansimarkup '<b>Bold</b>' '<r>Red</r>' |
| 211 | python -m ansimarkup '<b><r>Bold Red</r></b>' |
| 212 | python -m ansimarkup < input-with-markup.txt |
| 213 | echo '<b>Bold</b>' | python -m ansimarkup |
| 214 | |
| 215 | ### Logging formatter |
| 216 | |
| 217 | Ansimarkup also comes with a formatter for the standard library `logging` module. It can be used as: |
| 218 | |
| 219 | ``` python |
| 220 | import logging |
| 221 | from ansimarkup.logformatter import AnsiMarkupFormatter |
| 222 | |
| 223 | log = logging.getLogger() |
| 224 | hdl = logging.StreamHandler() |
| 225 | fmt = AnsiMarkupFormatter() |
| 226 | hdl.setFormatter(fmt) |
| 227 | log.addHandler(hdl) |
| 228 | |
| 229 | log.info("<b>bold text</b>") |
| 230 | ``` |
| 231 | |
| 232 | ### Windows |
| 233 | |
| 234 | Ansimarkup uses the [colorama] library internally, which means that |
| 235 | Windows support for ansi escape sequences is available by first running: |
| 236 | |
| 237 | ``` python |
| 238 | import colorama |
| 239 | colorama.init() |
| 240 | ``` |
| 241 | |
| 242 | For more information on Windows support, consult the \"Usage\" section |
| 243 | of the [colorama] documentation. |
| 244 | |
| 245 | ## Performance |
| 246 | |
| 247 | While the focus of ansimarkup is convenience, it does try to keep |
| 248 | processing to a minimum. The [benchmark.py] script attempts to benchmark |
| 249 | different ansi escape code libraries: |
| 250 | |
| 251 | Benchmark 1: <r><b>red bold</b></r> |
| 252 | colorama 0.0873 μs |
| 253 | termcolor 0.4854 μs |
| 254 | ansimarkup 1.5728 μs |
| 255 | rich 4.1645 μs |
| 256 | pastel 4.4223 μs |
| 257 | plumbum 6.7151 μs |
| 258 | |
| 259 | Benchmark 2: <r><b>red bold</b>red</r><b>bold</b> |
| 260 | colorama 0.1799 μs |
| 261 | termcolor 1.0695 μs |
| 262 | ansimarkup 2.2035 μs |
| 263 | rich 9.4981 μs |
| 264 | pastel 9.8800 μs |
| 265 | plumbum 15.2062 μs |
| 266 | |
| 267 | |
| 268 | ## Limitations |
| 269 | |
| 270 | Ansimarkup is a simple wrapper around [colorama]. It does very little in |
| 271 | the way of validating that markup strings are well-formed. This is a |
| 272 | conscious decision with the goal of keeping things simple and fast. |
| 273 | |
| 274 | Unbalanced nesting, such as in the following example, will produce |
| 275 | incorrect output: |
| 276 | |
| 277 | <r><Y>1</r>2</Y> |
| 278 | |
| 279 | ## Todo |
| 280 | |
| 281 | - Many corner cases remain to be fixed. |
| 282 | - More elaborate testing. The current test suite mostly covers the \"happy paths\". |
| 283 | - Replace `tag_list.index` in `sub_end` with something more efficient (i.e. something like an ordered MultiDict). |
| 284 | |
| 285 | ## Similar libraries |
| 286 | |
| 287 | - [pastel][]: bring colors to your terminal |
| 288 | - [plumbum.colors][]: small yet feature-rich library for shell script-like programs in Python |
| 289 | - [colr][]: easy terminal colors, with chainable methods |
| 290 | - [rich][]: rich text and beautiful formatting in the terminal (see `rich.print()` and `rich.markup.render()`) |
| 291 | |
| 292 | ## License |
| 293 | |
| 294 | Ansimarkup is released under the terms of the [Revised BSD License]. |
| 295 | |
| 296 | [tags.py]: https://github.com/gvalkov/python-ansimarkup/blob/main/ansimarkup/tags.py |
| 297 | [colorama]: https://pypi.python.org/pypi/colorama |
| 298 | [benchmark.py]: https://github.com/gvalkov/python-ansimarkup/blob/main/tests/benchmark.py |
| 299 | [pastel]: https://github.com/sdispater/pastel |
| 300 | [plumbum.colors]: https://plumbum.readthedocs.io/en/latest/cli.html#colors |
| 301 | [colr]: https://pypi.python.org/pypi/Colr/ |
| 302 | [rich]: https://github.com/Textualize/rich |
| 303 | [Revised BSD License]: https://github.com/gvalkov/python-ansimarkup/blob/main/LICENSE.txt |