123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- import sys
- import re
- from PyQt5 import QtCore, QtGui
- from pygments import highlight
- from pygments.lexers import *
- from pygments.formatter import Formatter
- from pygments.styles import get_all_styles, get_style_by_name
- import time
- def hex2QColor(c):
- r=int(c[0:2],16)
- g=int(c[2:4],16)
- b=int(c[4:6],16)
- return QtGui.QColor(r,g,b)
- class QFormatter(Formatter):
- def __init__(self, linenos=True, style="default"):
- Formatter.__init__(self)
- self.data=[]
- self.style = get_style_by_name(style)
-
-
-
-
-
-
-
- self.styles={}
- for token, style in self.style:
- qtf=QtGui.QTextCharFormat()
- if style['color']:
- qtf.setForeground(hex2QColor(style['color']))
- if style['bgcolor']:
- qtf.setBackground(hex2QColor(style['bgcolor']))
- if style['bold']:
- qtf.setFontWeight(QtGui.QFont.Bold)
- if style['italic']:
- qtf.setFontItalic(True)
- if style['underline']:
- qtf.setFontUnderline(True)
- self.styles[str(token)]=qtf
- def format(self, tokensource, outfile):
- global styles
-
- self.data=[]
-
-
-
- print(tokensource)
- for ttype, value in tokensource:
- l=len(value)
- t=str(ttype)
- self.data.extend([self.styles[t],]*l)
- class Highlighter(QtGui.QSyntaxHighlighter):
- def __init__(self, parent, mode):
- QtGui.QSyntaxHighlighter.__init__(self, parent)
- self.tstamp=time.time()
-
-
- if not mode == "md":
- self.formatter=QFormatter(linenos=True, style="monokai-hcb")
- else:
- self.formatter=QFormatter(linenos=False, style="github")
- self.lexer=get_lexer_by_name(mode)
- def highlightBlock(self, text):
- """Takes a block, applies format to the document.
- according to what's in it.
- """
-
-
-
- cb = self.currentBlock()
- p = cb.position()
-
-
-
- text=str(self.document().toPlainText())+'\n'
-
-
-
- highlight(text,self.lexer,self.formatter)
-
-
-
- for i in range(len(str(text))):
- try:
- self.setFormat(i,1,self.formatter.data[p+i])
- except IndexError:
- pass
-
-
- self.tstamp=time.time()
|