Source

syntaxhighlighter / doc / usage.rst

Full commit

How to use the module

As an example a very simple highlighter for HTML will be shown. It contains three different partitions: comments, tags and text.

The object oriented way

The OO-way is useful to understand what is going on internally and to add custom behaviour:

First import the required classes:

from highlighter import Format, Partition, PartitionScanner, Token, Scanner, SyntaxHighlighter

Now define some formats:

comment_fmt = Format("comment", color="#a0a0a0", italic=True)
tag_fmt     = Format("tag", color="blue", bold=True)
attr_fmt    = Format("attr", color="lightblue")
value_fmt   = Format("value", color="lightblue", italic=True)
text_fmt    = Format("text", color="black")
formats = [ comment_fmt, tag_fmt, text_fmt, attr_fmt, value_fmt ]

Create the partition scanner

comment_part = Partition("comment", "<!--", "-->", is_multiline=True)
tag_part     = Partition("tag", "<", ">", is_multiline=True)

ps           = PartitionScanner([comment_part, tag_part])

Create a Scanner for the tag partition

attr_token    = Token("attr", "[A-Za-z_]\w*")
equals_token  = Token("equals", "=")
value_token   = Token("value", '"[^"]*"')
tag_scanner   = Scanner([attr_token, equals_token, value_token])

Now you can use the highlighter:

if __name__ == "__main__":
  from PyQt4.QtGui import QApplication, QPlainTextEdit
  app = QApplication([])
      edit = QPlainTextEdit(None)
      sh = SyntaxHighlighter(edit.document(),
        ps, {"tag":tag_scanner}, formats)
      edit.resize(800, 600)
      edit.setPlainText('<!-- comment--> text <tag attr="value">')
      edit.show()
      app.exec_()

The descriptive way

from highlighter import SyntaxHighlighter

formats = [
  ("comment", ("#a0a0a0", False, True)),
  ("tag", ("blue", True)),
  ("attr", ("lightblue")),
  ("value", dict(color="lightblue", italic=True)),
  ("text", ("black",))
]

parts = [
  ("comment", "<!--", "-->", True),
  ("tag", "<", ">", True)
]


tag_scanner = [
  ("attr", "[A-Za-z_]\w*"),
  ("equals", "="),
  ("value", '"[^"]*"')
]



if __name__ == "__main__":
      from PyQt4.QtGui import QApplication, QPlainTextEdit
      app = QApplication([])
      edit = QPlainTextEdit(None)
      sh = SyntaxHighlighter(edit.document(), parts, {"tag":tag_scanner}, formats)
      edit.resize(800, 600)
      edit.setPlainText('<!-- comment--> text <tag attr="value">')
      edit.show()
      app.exec_()

As you see the lists, tuples and dicts get converted into Format, Partion, PartionScanner, Token and Scanner instances.