Ejemplo n.º 1
1
 def do_format_block(self):
     name = self.sender().block_name
     with self.editing_cursor() as c:
         bf = QTextBlockFormat()
         cf = QTextCharFormat()
         bcf = c.blockCharFormat()
         lvl = self.level_for_block_type(name)
         wt = QFont.Weight.Bold if lvl else None
         adjust = (0, 3, 2, 1, 0, -1, -1)[lvl]
         pos = None
         if not c.hasSelection():
             pos = c.position()
             c.movePosition(QTextCursor.MoveOperation.StartOfBlock,
                            QTextCursor.MoveMode.MoveAnchor)
             c.movePosition(QTextCursor.MoveOperation.EndOfBlock,
                            QTextCursor.MoveMode.KeepAnchor)
         # margin values are taken from qtexthtmlparser.cpp
         hmargin = 0
         if name == 'blockquote':
             hmargin = 40
         tmargin = bmargin = 12
         if name == 'h1':
             tmargin, bmargin = 18, 12
         elif name == 'h2':
             tmargin, bmargin = 16, 12
         elif name == 'h3':
             tmargin, bmargin = 14, 12
         elif name == 'h4':
             tmargin, bmargin = 12, 12
         elif name == 'h5':
             tmargin, bmargin = 12, 4
         bf.setLeftMargin(hmargin), bf.setRightMargin(hmargin)
         bf.setTopMargin(tmargin), bf.setBottomMargin(bmargin)
         bf.setHeadingLevel(lvl)
         if adjust:
             bcf.setProperty(QTextFormat.Property.FontSizeAdjustment,
                             adjust)
             cf.setProperty(QTextFormat.Property.FontSizeAdjustment, adjust)
         if wt:
             bcf.setProperty(QTextFormat.Property.FontWeight, wt)
             cf.setProperty(QTextFormat.Property.FontWeight, wt)
         c.setBlockCharFormat(bcf)
         c.mergeCharFormat(cf)
         c.mergeBlockFormat(bf)
         if pos is not None:
             c.setPosition(pos)
Ejemplo n.º 2
0
 def do_insert_link(self, *args):
     link, name, is_image = self.ask_link()
     if not link:
         return
     url = self.parse_link(link)
     if url.isValid():
         url = unicode_type(url.toString(NO_URL_FORMATTING))
         self.focus_self()
         with self.editing_cursor() as c:
             if is_image:
                 c.insertImage(url)
             else:
                 name = name or url
                 fmt = QTextCharFormat()
                 fmt.setAnchor(True)
                 fmt.setAnchorHref(url)
                 fmt.setFontUnderline(True)
                 fmt.setForeground(QBrush(QColor('blue')))
                 prev_fmt = c.charFormat()
                 c.mergeCharFormat(fmt)
                 c.insertText(url)
                 c.setCharFormat(prev_fmt)
     else:
         error_dialog(self, _('Invalid URL'),
                      _('The url %r is invalid') % link, show=True)
Ejemplo n.º 3
0
 def __init__(self, right=False, parent=None, show_open_in_editor=False):
     PlainTextEdit.__init__(self, parent)
     self.setFrameStyle(0)
     self.show_open_in_editor = show_open_in_editor
     self.side_margin = 0
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     self.customContextMenuRequested.connect(self.show_context_menu)
     self.setFocusPolicy(Qt.NoFocus)
     self.right = right
     self.setReadOnly(True)
     self.setLineWrapMode(self.WidgetWidth)
     font = self.font()
     ff = tprefs['editor_font_family']
     if ff is None:
         ff = default_font_family()
     font.setFamily(ff)
     font.setPointSize(tprefs['editor_font_size'])
     self.setFont(font)
     self.calculate_metrics()
     self.setTabStopWidth(tprefs['editor_tab_stop_width'] * self.space_width)
     font = self.heading_font = QFont(self.font())
     font.setPointSize(int(tprefs['editor_font_size'] * 1.5))
     font.setBold(True)
     theme = get_theme(tprefs['editor_theme'])
     pal = self.palette()
     pal.setColor(pal.Base, theme_color(theme, 'Normal', 'bg'))
     pal.setColor(pal.AlternateBase, theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'Normal', 'fg'))
     pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg'))
     pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.viewport().setCursor(Qt.ArrowCursor)
     self.line_number_area = LineNumbers(self)
     self.blockCountChanged[int].connect(self.update_line_number_area_width)
     self.updateRequest.connect(self.update_line_number_area)
     self.line_number_palette = pal = QPalette()
     pal.setColor(pal.Base, theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(pal.BrightText, theme_color(theme, 'LineNrC', 'fg'))
     self.line_number_map = LineNumberMap()
     self.search_header_pos = 0
     self.changes, self.headers, self.images = [], [], OrderedDict()
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff), self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.diff_backgrounds = {
         'replace' : theme_color(theme, 'DiffReplace', 'bg'),
         'insert'  : theme_color(theme, 'DiffInsert', 'bg'),
         'delete'  : theme_color(theme, 'DiffDelete', 'bg'),
         'replacereplace': theme_color(theme, 'DiffReplaceReplace', 'bg'),
         'boundary': QBrush(theme_color(theme, 'Normal', 'fg'), Qt.Dense7Pattern),
     }
     self.diff_foregrounds = {
         'replace' : theme_color(theme, 'DiffReplace', 'fg'),
         'insert'  : theme_color(theme, 'DiffInsert', 'fg'),
         'delete'  : theme_color(theme, 'DiffDelete', 'fg'),
         'boundary': QColor(0, 0, 0, 0),
     }
     for x in ('replacereplace', 'insert', 'delete'):
         f = QTextCharFormat()
         f.setBackground(self.diff_backgrounds[x])
         setattr(self, '%s_format' % x, f)
Ejemplo n.º 4
0
 def __init__(self, right=False, parent=None, show_open_in_editor=False):
     PlainTextEdit.__init__(self, parent)
     self.setFrameStyle(0)
     self.show_open_in_editor = show_open_in_editor
     self.side_margin = 0
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     self.customContextMenuRequested.connect(self.show_context_menu)
     self.setFocusPolicy(Qt.NoFocus)
     self.right = right
     self.setReadOnly(True)
     self.setLineWrapMode(self.WidgetWidth)
     font = self.font()
     ff = tprefs['editor_font_family']
     if ff is None:
         ff = default_font_family()
     font.setFamily(ff)
     font.setPointSize(tprefs['editor_font_size'])
     self.setFont(font)
     self.calculate_metrics()
     self.setTabStopWidth(tprefs['editor_tab_stop_width'] * self.space_width)
     font = self.heading_font = QFont(self.font())
     font.setPointSize(int(tprefs['editor_font_size'] * 1.5))
     font.setBold(True)
     theme = get_theme(tprefs['editor_theme'])
     pal = self.palette()
     pal.setColor(pal.Base, theme_color(theme, 'Normal', 'bg'))
     pal.setColor(pal.AlternateBase, theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'Normal', 'fg'))
     pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg'))
     pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.viewport().setCursor(Qt.ArrowCursor)
     self.line_number_area = LineNumbers(self)
     self.blockCountChanged[int].connect(self.update_line_number_area_width)
     self.updateRequest.connect(self.update_line_number_area)
     self.line_number_palette = pal = QPalette()
     pal.setColor(pal.Base, theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(pal.BrightText, theme_color(theme, 'LineNrC', 'fg'))
     self.line_number_map = LineNumberMap()
     self.search_header_pos = 0
     self.changes, self.headers, self.images = [], [], OrderedDict()
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff), self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.diff_backgrounds = {
         'replace' : theme_color(theme, 'DiffReplace', 'bg'),
         'insert'  : theme_color(theme, 'DiffInsert', 'bg'),
         'delete'  : theme_color(theme, 'DiffDelete', 'bg'),
         'replacereplace': theme_color(theme, 'DiffReplaceReplace', 'bg'),
         'boundary': QBrush(theme_color(theme, 'Normal', 'fg'), Qt.Dense7Pattern),
     }
     self.diff_foregrounds = {
         'replace' : theme_color(theme, 'DiffReplace', 'fg'),
         'insert'  : theme_color(theme, 'DiffInsert', 'fg'),
         'delete'  : theme_color(theme, 'DiffDelete', 'fg'),
         'boundary': QColor(0, 0, 0, 0),
     }
     for x in ('replacereplace', 'insert', 'delete'):
         f = QTextCharFormat()
         f.setBackground(self.diff_backgrounds[x])
         setattr(self, '%s_format' % x, f)
Ejemplo n.º 5
0
    def hline(self):
        """
        Insert horizontal line
        """
        # Tag HR is not correctly displayed  in QTextview
        cur_char_fmt = self._text_edit_cursor.charFormat()
        cur_block_fmt = self._text_edit_cursor.blockFormat()
        if bool(self._text_edit_cursor.currentTable()):
            self._text_edit_cursor.insertBlock(cur_block_fmt, cur_char_fmt)

        block_fmt = QTextBlockFormat()
        block_fmt.setTopMargin(5)
        block_fmt.setBottomMargin(5)
        block_fmt.setAlignment(Qt.AlignLeft)
        block_fmt.setBackground(QBrush(QColor("#C1C1C1")))

        char_format = QTextCharFormat()
        char_format.setFont(QFont("Arial", 1))

        self._text_edit_cursor.insertBlock(block_fmt, char_format)
        self._text_edit_cursor.insertText(" ")

        self._text_edit_cursor.insertBlock(cur_block_fmt, cur_char_fmt)

        self.change(self._text_edit_cursor)
Ejemplo n.º 6
0
 def do_background(self):
     col = QColorDialog.getColor(Qt.white, self,
             _('Choose background color'), QColorDialog.ShowAlphaChannel)
     if col.isValid():
         fmt = QTextCharFormat()
         fmt.setBackground(QBrush(col))
         with self.editing_cursor() as c:
             c.mergeCharFormat(fmt)
Ejemplo n.º 7
0
 def do_color(self):
     col = QColorDialog.getColor(
         Qt.GlobalColor.black, self, _('Choose foreground color'),
         QColorDialog.ColorDialogOption.ShowAlphaChannel)
     if col.isValid():
         fmt = QTextCharFormat()
         fmt.setForeground(QBrush(col))
         with self.editing_cursor() as c:
             c.mergeCharFormat(fmt)
Ejemplo n.º 8
0
 def __init__( self, pattern, color, style ):
     if isinstance(pattern,basestring):
         self.pattern = re.compile(pattern)
     else:
         self.pattern=pattern
     charfmt = QTextCharFormat()
     brush = QBrush(color, style)
     charfmt.setForeground(brush)
     self.highlight = charfmt
Ejemplo n.º 9
0
    def do_insert_link(self, *args):
        link, name, is_image = self.ask_link()
        if not link:
            return
        url = self.parse_link(link)
        if url.isValid():
            url = unicode_type(url.toString(NO_URL_FORMATTING))
            self.focus_self()
            with self.editing_cursor() as c:
                if is_image:
                    c.insertImage(url)
                else:
                    oldfmt = QTextCharFormat(c.charFormat())
                    fmt = QTextCharFormat()
                    fmt.setAnchor(True)
                    fmt.setAnchorHref(url)
                    fmt.setForeground(QBrush(self.palette().color(QPalette.Link)))
                    if name or not c.hasSelection():
                        c.mergeCharFormat(fmt)
                        c.insertText(name or url)
                    else:
                        pos, anchor = c.position(), c.anchor()
                        start, end = min(pos, anchor), max(pos, anchor)
                        for i in range(start, end):
                            cur = self.textCursor()
                            cur.setPosition(i), cur.setPosition(i + 1, c.KeepAnchor)
                            cur.mergeCharFormat(fmt)
                    c.setPosition(c.position())
                    c.setCharFormat(oldfmt)

        else:
            error_dialog(self, _('Invalid URL'),
                         _('The url %r is invalid') % link, show=True)
Ejemplo n.º 10
0
    def highlightBlock(self, text):
        if not self.dict:
            return

        format = QTextCharFormat()
        format.setUnderlineColor(Qt.red)
        format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

        for word_object in re.finditer(self.WORDS, text):
            if not self.dict.check(word_object.group()):
                self.setFormat(word_object.start(),
                    word_object.end() - word_object.start(), format)
Ejemplo n.º 11
0
def parse_text_formatting(text):
    pos = 0
    tokens = []
    for m in re.finditer(r'</?([a-zA-Z1-6]+)/?>', text):
        q = text[pos:m.start()]
        if q:
            tokens.append((False, q))
        tokens.append((True, (m.group(1).lower(), '/' in m.group()[:2])))
        pos = m.end()
    if tokens:
        if text[pos:]:
            tokens.append((False, text[pos:]))
    else:
        tokens = [(False, text)]

    ranges, open_ranges, text = [], [], []
    offset = 0
    for is_tag, tok in tokens:
        if is_tag:
            tag, closing = tok
            if closing:
                if open_ranges:
                    r = open_ranges.pop()
                    r[-1] = offset - r[-2]
                    if r[-1] > 0:
                        ranges.append(r)
            else:
                if tag in {'b', 'strong', 'i', 'em'}:
                    open_ranges.append([tag, offset, -1])
        else:
            offset += len(tok.replace('&amp;', '&'))
            text.append(tok)
    text = ''.join(text)
    formats = []
    for tag, start, length in chain(ranges, open_ranges):
        fmt = QTextCharFormat()
        if tag in {'b', 'strong'}:
            fmt.setFontWeight(QFont.Bold)
        elif tag in {'i', 'em'}:
            fmt.setFontItalic(True)
        else:
            continue
        if length == -1:
            length = len(text) - start
        if length > 0:
            r = QTextLayout.FormatRange()
            r.format = fmt
            r.start, r.length = start, length
            formats.append(r)
    return text, formats
Ejemplo n.º 12
0
 def __init__( self, pattern, color,
               weight=QFont.Normal,
               style=Qt.SolidPattern,
               blocknum=0):
     if isinstance(pattern,basestring):
         self.pattern = re.compile(pattern)
     else:
         self.pattern=pattern
     charfmt = QTextCharFormat()
     brush = QBrush(color, style)
     charfmt.setForeground(brush)
     charfmt.setFontWeight(weight)
     self.highlight = charfmt
     self.blocknum=blocknum
Ejemplo n.º 13
0
    def __init__(self, controller):
        super().__init__()
        formc = QTextCharFormat()
        formc.setFontItalic(True)
        formc.setFontWeight(3)
        form = QTextBlockFormat()
        form.setLineHeight(200, 1)


        cur = self.textCursor()
        cur.insertText('', self.format_p)
        new_speech_signal = QObject()
        controller.speech.connect(self.new_speech_signal.emit)
        controller.speech.start()
        self.new_speech_signal.connect(cur.insertText)
Ejemplo n.º 14
0
    def setFontFamily(self, family):
        """Override. Set font family."""

        undoState = self.isUndoRedoEnabled()
        self.setUndoRedoEnabled(False)
        mod = self.document().isModified()
        fmt = QTextCharFormat()
        fmt.setFontFamily(family)
        cursor = self.textCursor()
        self.selectAll()
        super().setFontFamily(family)
        cursor2 = self.textCursor()
        cursor2.clearSelection()
        self.setTextCursor(cursor2)
        self.setTextCursor(cursor)
        self.document().setModified(mod)
        self.setUndoRedoEnabled(undoState)
Ejemplo n.º 15
0
    def setFontPointSize(self, pointSize):
        """Override. Set font size."""

        pointSize = float(pointSize)
        if pointSize > 0:
            undoState = self.isUndoRedoEnabled()
            self.setUndoRedoEnabled(False)
            mod = self.document().isModified()
            fmt = QTextCharFormat()
            fmt.setFontPointSize(pointSize)
            cursor = self.textCursor()
            self.selectAll()
            super().setFontPointSize(pointSize)
            cursor2 = self.textCursor()
            cursor2.clearSelection()
            self.setTextCursor(cursor2)
            self.setTextCursor(cursor)
            self.document().setModified(mod)
            self.setUndoRedoEnabled(undoState)
Ejemplo n.º 16
0
def format_style(color, style=''):
    """Return a QTextCharFormat with the given attributes."""
    _color = QColor()
    _color.setNamedColor(color)

    _format = QTextCharFormat()
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format
Ejemplo n.º 17
0
 def check_spelling(text, tlen, fmt, locale, sfmt, store_locale):
     split_ans = []
     ppos = 0
     r, a = dictionaries.recognized, split_ans.append
     for start, length in split_into_words_and_positions(text, lang=locale.langcode):
         if start > ppos:
             a((start - ppos, fmt))
         ppos = start + length
         recognized = r(text[start:ppos], locale)
         if recognized:
             a((length, fmt))
         else:
             if store_locale:
                 s = QTextCharFormat(sfmt)
                 s.setProperty(SPELL_LOCALE_PROPERTY, locale)
                 a((length, s))
             else:
                 a((length, sfmt))
     if ppos < tlen:
         a((tlen - ppos, fmt))
     return split_ans
Ejemplo n.º 18
0
def process_text(state, text, nbsp_format, spell_format, user_data):
    ans = []
    fmt = None
    if state.is_bold or state.is_italic:
        fmt = syntax_text_char_format()
        if state.is_bold:
            fmt.setFontWeight(QFont.Bold)
        if state.is_italic:
            fmt.setFontItalic(True)
    last = 0
    for m in nbsp_pat.finditer(text):
        ans.extend([(m.start() - last, fmt),
                    (m.end() - m.start(), nbsp_format)])
        last = m.end()
    if not ans:
        ans = [(len(text), fmt)]
    elif last < len(text):
        ans.append((len(text) - last, fmt))

    if do_spell_check and state.tags and user_data.tag_ok_for_spell(
            state.tags[-1].name):
        split_ans = []
        locale = state.current_lang or dictionaries.default_locale
        sfmt = QTextCharFormat(spell_format)
        if fmt is not None:
            sfmt.merge(fmt)

        tpos = 0
        for tlen, fmt in ans:
            if fmt is nbsp_format:
                split_ans.append((tlen, fmt))
            else:
                split_ans.extend(
                    check_spelling(text[tpos:tpos + tlen], tlen, fmt, locale,
                                   sfmt, store_locale.enabled))

            tpos += tlen
        ans = split_ans

    return ans
Ejemplo n.º 19
0
    def _refreshTextFormat(self):
        if not self._webView:
            return

        textFormat = []  # typedef QList<QTextLayout::FormatRange>
        if self._webView.url().isEmpty():
            hostName = QUrl(self.text()).host()
        else:
            hostName = self._webView.url().host()

        if hostName:
            hostPos = self.text().find(hostName)
            if hostPos > 0:
                format_ = QTextCharFormat()
                palette = self.palette()
                color = Colors.mid(palette.color(QPalette.Base),
                                   palette.color(QPalette.Text), 1, 1)
                format_.setForeground(color)

                schemePart = QTextLayout.FormatRange()
                schemePart.start = 0
                schemePart.length = hostPos
                schemePart.format = format_

                hostPart = QTextLayout.FormatRange()
                hostPart.start = hostPos
                hostPart.length = len(hostName)

                remainingPart = QTextLayout.FormatRange()
                remainingPart.start = hostPos + len(hostName)
                remainingPart.length = len(self.text()) - remainingPart.start
                remainingPart.format = format_

                textFormat.append(schemePart)
                textFormat.append(hostPart)
                textFormat.append(remainingPart)

        self.setTextFormat(textFormat)
Ejemplo n.º 20
0
def process_text(state, text, nbsp_format, spell_format, user_data):
    ans = []
    fmt = None
    if state.is_bold or state.is_italic:
        fmt = syntax_text_char_format()
        if state.is_bold:
            fmt.setFontWeight(QFont.Bold)
        if state.is_italic:
            fmt.setFontItalic(True)
    last = 0
    for m in nbsp_pat.finditer(text):
        ans.extend([(m.start() - last, fmt), (m.end() - m.start(), nbsp_format)])
        last = m.end()
    if not ans:
        ans = [(len(text), fmt)]
    elif last < len(text):
        ans.append((len(text) - last, fmt))

    if do_spell_check and state.tags and user_data.tag_ok_for_spell(state.tags[-1].name):
        split_ans = []
        locale = state.current_lang or dictionaries.default_locale
        sfmt = QTextCharFormat(spell_format)
        if fmt is not None:
            sfmt.merge(fmt)

        tpos = 0
        for tlen, fmt in ans:
            if fmt is nbsp_format:
                split_ans.append((tlen, fmt))
            else:
                split_ans.extend(
                    check_spelling(text[tpos : tpos + tlen], tlen, fmt, locale, sfmt, store_locale.enabled)
                )

            tpos += tlen
        ans = split_ans

    return ans
 def highlightBlock(self, text):            # Function for formatting
     if not self.dict:                      # the text inside this text 
         return                             # edit field, sets the format
     formats = QTextCharFormat()            # of the text that not match
     formats.setUnderlineColor(Qt.red)      # to the dicts. Red underline.
     formats.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
     for w in re.finditer(self.words, text):
         if not self.dict.check(w.group()):
             self.setFormat(w.start(), w.end() - w.start(), formats)
Ejemplo n.º 22
0
    def highlightBlock(self, text):
        if not self.dict:
            return

        format = QTextCharFormat()
        format.setUnderlineColor(Qt.red)
        format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

        for word_object in re.finditer(self.WORDS, text):
            if not self.dict.check(word_object.group()):
                self.setFormat(word_object.start(),
                               word_object.end() - word_object.start(), format)
Ejemplo n.º 23
0
 def __init__( self, pattern, color,
               weight=QFont.Normal,
               style=Qt.SolidPattern,
               blocknum=0):
     if isinstance(pattern, string_types):
         self.pattern = re.compile(pattern)
     else:
         self.pattern=pattern
     charfmt = QTextCharFormat()
     brush = QBrush(color, style)
     charfmt.setForeground(brush)
     charfmt.setFontWeight(weight)
     self.highlight = charfmt
     self.blocknum=blocknum
Ejemplo n.º 24
0
def parse_text_formatting(text):
    pos = 0
    tokens = []
    for m in re.finditer(r'</?([a-zA-Z1-6]+)/?>', text):
        q = text[pos:m.start()]
        if q:
            tokens.append((False, q))
        tokens.append((True, (m.group(1).lower(), '/' in m.group()[:2])))
        pos = m.end()
    if tokens:
        if text[pos:]:
            tokens.append((False, text[pos:]))
    else:
        tokens = [(False, text)]

    ranges, open_ranges, text = [], [], []
    offset = 0
    for is_tag, tok in tokens:
        if is_tag:
            tag, closing = tok
            if closing:
                if open_ranges:
                    r = open_ranges.pop()
                    r[-1] = offset - r[-2]
                    if r[-1] > 0:
                        ranges.append(r)
            else:
                if tag in {'b', 'strong', 'i', 'em'}:
                    open_ranges.append([tag, offset, -1])
        else:
            offset += len(tok)
            text.append(tok)
    text = ''.join(text)
    formats = []
    for tag, start, length in chain(ranges, open_ranges):
        fmt = QTextCharFormat()
        if tag in {'b', 'strong'}:
            fmt.setFontWeight(QFont.Bold)
        elif tag in {'i', 'em'}:
            fmt.setFontItalic(True)
        else:
            continue
        if length == -1:
            length = len(text) - start
        if length > 0:
            r = QTextLayout.FormatRange()
            r.format = fmt
            r.start, r.length = start, length
            formats.append(r)
    return text, formats
Ejemplo n.º 25
0
 def spell_property(sfmt, locale):
     s = QTextCharFormat(sfmt)
     s.setProperty(SPELL_LOCALE_PROPERTY, locale)
     return s
Ejemplo n.º 26
0
    def initializeFormats(cls):
        if cls.Formats:
            return
        baseFormat = QTextCharFormat()
        baseFormat.setFontFamily('monospace')
        baseFormat.setFontPointSize(11)
        for name, color, bold, italic in (
                ("normal", "#000000", False, False),
                ("keyword", "#000080", True, False),
                ("builtin", "#0000A0", False, False),
                ("constant", "#0000C0", False, False),
                ("decorator", "#0000E0", False, False),
                ("comment", "#007F00", False, True),
                ("string", "#808000", False, False),
                ("number", "#924900", False, False),
                ("error", "#FF0000", False, False),
                ("pyqt", "#50621A", False, False)):

            format = QTextCharFormat(baseFormat)
            format.setForeground(QColor(color))
            if bold:
                format.setFontWeight(QFont.Bold)
            format.setFontItalic(italic)
            cls.Formats[name] = format
Ejemplo n.º 27
0
 def do_remove_format(self):
     with self.editing_cursor() as c:
         c.setBlockFormat(QTextBlockFormat())
         c.setCharFormat(QTextCharFormat())
Ejemplo n.º 28
0
 def do_vertical_align(self, which):
     with self.editing_cursor() as c:
         fmt = QTextCharFormat()
         fmt.setVerticalAlignment(which)
         c.mergeCharFormat(fmt)
Ejemplo n.º 29
0
 def do_strikethrough(self):
     with self.editing_cursor() as c:
         fmt = QTextCharFormat()
         fmt.setFontStrikeOut(not c.charFormat().fontStrikeOut())
         c.mergeCharFormat(fmt)
Ejemplo n.º 30
0
#!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
                        print_function)

__license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'

from PyQt5.Qt import QTextCharFormat

NULL_FMT = QTextCharFormat()

_pyg_map = None


def pygments_map():
    global _pyg_map
    if _pyg_map is None:
        from pygments.token import Token
        _pyg_map = {
            Token: None,
            Token.Comment: 'Comment',
            Token.Comment.Preproc: 'PreProc',
            Token.String: 'String',
            Token.Number: 'Number',
            Token.Keyword.Type: 'Type',
            Token.Keyword: 'Keyword',
            Token.Name.Builtin: 'Identifier',
            Token.Operator: 'Statement',
            Token.Name.Function: 'Function',
            Token.Literal: 'Constant',
Ejemplo n.º 31
0
 def base_fmt(self):
     fmt = QTextCharFormat()
     fmt.setFontFamily('monospace')
     return fmt
Ejemplo n.º 32
0
 def do_bold(self):
     with self.editing_cursor() as c:
         fmt = QTextCharFormat()
         fmt.setFontWeight(
             QFont.Bold if c.charFormat().fontWeight() != QFont.Bold else QFont.Normal)
         c.mergeCharFormat(fmt)
Ejemplo n.º 33
0
    def initializeFormats(self):
        Config = self.Config
        Config["fontfamily"] = "monospace"
        for name, color, bold, italic in (
                ("normal", "#000000", False, False),
                ("keyword", "#000080", True, False),
                ("builtin", "#0000A0", False, False),
                ("comment", "#007F00", False, True),
                ("string", "#808000", False, False),
                ("number", "#924900", False, False),
                ("lparen", "#000000", True, True),
                ("rparen", "#000000", True, True)):
            Config["%sfontcolor" % name] = color
            Config["%sfontbold" % name] = bold
            Config["%sfontitalic" % name] = italic
        baseFormat = QTextCharFormat()
        baseFormat.setFontFamily(Config["fontfamily"])
        Config["fontsize"] = gprefs['gpm_template_editor_font_size']
        baseFormat.setFontPointSize(Config["fontsize"])

        for name in ("normal", "keyword", "builtin", "comment",
                     "string", "number", "lparen", "rparen"):
            format = QTextCharFormat(baseFormat)
            format.setForeground(QColor(Config["%sfontcolor" % name]))
            if Config["%sfontbold" % name]:
                format.setFontWeight(QFont.Bold)
            format.setFontItalic(Config["%sfontitalic" % name])
            self.Formats[name] = format
Ejemplo n.º 34
0
def syntax_text_char_format(*args):
    ans = QTextCharFormat(*args)
    ans.setProperty(SYNTAX_PROPERTY, True)
    return ans
Ejemplo n.º 35
0
    def initializeFormats(cls):
        baseFormat = QTextCharFormat()
        baseFormat.setFontFamily('monospace')
        p = QApplication.instance().palette()
        for name, color, bold, italic in (("normal", None, False, False),
                                          ("keyword", p.color(p.Link).name(),
                                           True, False),
                                          ("builtin", p.color(p.Link).name(),
                                           False, False),
                                          ("constant", p.color(p.Link).name(),
                                           False, False),
                                          ("decorator", "#0000E0", False,
                                           False), ("comment", "#007F00",
                                                    False, True),
                                          ("string", "#808000", False, False),
                                          ("number", "#924900", False,
                                           False), ("error", "#FF0000", False,
                                                    False), ("pyqt", "#50621A",
                                                             False, False)):

            fmt = QTextCharFormat(baseFormat)
            if color is not None:
                fmt.setForeground(QColor(color))
            if bold:
                fmt.setFontWeight(QFont.Bold)
            if italic:
                fmt.setFontItalic(italic)
            cls.Formats[name] = fmt
Ejemplo n.º 36
0
    def addNode(self, node):
        if type(node) == Paragraph:
            self.paraFormat = self.formatManager.getFormat(node.style)

            # NOTE: "The block char format is the format used when inserting 
            #        text at the beginning of an empty block."
            #       See also below.
            self.cursor.insertBlock(self.paraFormat.getBlockFormat(), self.paraFormat.getCharFormat())
            # self.cursor.insertFragment(QTextDocumentFragment.fromPlainText(''))

            if self.listLevel > 0:
                # TODO: use list style from list node - requires a stack, though ...
                listStyle = ('itemizedlist', 'level', str(self.listLevel))
                newList = self.cursor.createList(self.formatManager.getFormat(listStyle).getListFormat())
            for n in node.children:
                self.addNode(n)

        elif type(node) == List:
            self.listLevel += 1
            for n in node.children:
                self.addNode(n)
            self.listLevel -= 1

        elif type(node) is ImageFragment:
            imageObject = ImageObject()
            imagePath = os.path.join(self.contentPath, node.image)
            imageObject.setName(imagePath)

            imageObjectFormat = QTextCharFormat()
            imageObjectFormat.setObjectType(QTextFormat.UserObject + 1)
            imageObjectFormat.setProperty(QTextFormat.UserProperty + 1, imageObject)
            self.cursor.insertText('\ufffc', imageObjectFormat);

        elif type(node) is MathFragment:
            mathFormula = MathFormulaObject()
            mathFormula.setFormula(node.text)
            mathFormula.image = node.image #  renderFormula()

            mathObjectFormat = QTextCharFormat()
            mathObjectFormat.setObjectType(QTextFormat.UserObject + 1)
            mathObjectFormat.setVerticalAlignment(QTextCharFormat.AlignMiddle)
            mathObjectFormat.setProperty(QTextFormat.UserProperty + 1, mathFormula)
            self.cursor.insertText('\ufffc', mathObjectFormat);
        elif type(node) is TextFragment:
            text = node.text.replace('\n', '\u2028')
            if node.href is not None:
                fmt = self.formatManager.getFormat(('link', None, None))   # TODO!
                charFmt = fmt.getCharFormat()
                charFmt.setAnchorHref(node.href)
                self.cursor.insertText(text, charFmt)
            else:
                # "The block char format is the format used when inserting text at the beginning of an empty block.
                # Hence, the block char format is only useful for the first fragment -
                # once a fragment is inserted with a different style, and afterwards
                # another fragment is inserted with no specific style, we need to reset
                # the char format to the block's char format explicitly!
    
                if node.style is not None:
                    fmt = self.formatManager.getFormat(node.style)
                else:
                    fmt = self.paraFormat

                self.cursor.insertText(text, fmt.getCharFormat())
Ejemplo n.º 37
0
    def highlightBlock(self, text):
        words = re.compile('[^_\\W]+', flags=re.UNICODE)

        char_format = QTextCharFormat()
        char_format.setUnderlineColor(Qt.red)
        char_format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

        # collect data for checking
        mark = []
        for match in words.finditer(text):
            final_format = QTextCharFormat()
            final_format.merge(char_format)
            final_format.merge(self.format(match.start()))

            if self._dictionary.word_needs_no_verification(match.group(0)):
                continue

            mark.append((match.group(0).lower(), match.start(),
                         match.end() - match.start(), final_format))

        # word check
        for word, start, length, fmt in mark:
            if not self._dictionary.check_word(word):
                self.setFormat(start, length, fmt)
Ejemplo n.º 38
0
 def spell_property(sfmt, locale):
     s = QTextCharFormat(sfmt)
     s.setProperty(SPELL_LOCALE_PROPERTY, locale)
     return s
Ejemplo n.º 39
0
 def do_italic(self):
     with self.editing_cursor() as c:
         fmt = QTextCharFormat()
         fmt.setFontItalic(not c.charFormat().fontItalic())
         c.mergeCharFormat(fmt)
Ejemplo n.º 40
0
    def initializeFormats(self):
        Config = self.Config
        Config["fontfamily"] = "monospace"
        pal = QApplication.instance().palette()
        for name, color, bold, italic in (
                ("normal", None, False, False),
                ("keyword", pal.color(pal.Link).name(), True, False),
                ("builtin", pal.color(pal.Link).name(), False, False),
                ("comment", "#007F00", False, True),
                ("string", "#808000", False, False),
                ("number", "#924900", False, False),
                ("lparen", None, True, True),
                ("rparen", None, True, True)):
            Config["%sfontcolor" % name] = color
            Config["%sfontbold" % name] = bold
            Config["%sfontitalic" % name] = italic
        baseFormat = QTextCharFormat()
        baseFormat.setFontFamily(Config["fontfamily"])
        Config["fontsize"] = gprefs['gpm_template_editor_font_size']
        baseFormat.setFontPointSize(Config["fontsize"])

        for name in ("normal", "keyword", "builtin", "comment",
                     "string", "number", "lparen", "rparen"):
            format = QTextCharFormat(baseFormat)
            col = Config["%sfontcolor" % name]
            if col:
                format.setForeground(QColor(col))
            if Config["%sfontbold" % name]:
                format.setFontWeight(QFont.Bold)
            format.setFontItalic(Config["%sfontitalic" % name])
            self.Formats[name] = format
Ejemplo n.º 41
0
 def do_underline(self):
     with self.editing_cursor() as c:
         fmt = QTextCharFormat()
         fmt.setFontUnderline(not c.charFormat().fontUnderline())
         c.mergeCharFormat(fmt)
Ejemplo n.º 42
0
    def initializeFormats(cls):
        if cls.Formats:
            return
        baseFormat = QTextCharFormat()
        baseFormat.setFontFamily('monospace')
        baseFormat.setFontPointSize(11)
        for name, color, bold, italic in (
                ("normal", "#000000", False, False),
                ("keyword", "#000080", True, False),
                ("builtin", "#0000A0", False, False),
                ("constant", "#0000C0", False, False),
                ("decorator", "#0000E0", False, False),
                ("comment", "#007F00", False, True),
                ("string", "#808000", False, False),
                ("number", "#924900", False, False),
                ("error", "#FF0000", False, False),
                ("pyqt", "#50621A", False, False)):

            format = QTextCharFormat(baseFormat)
            format.setForeground(QColor(color))
            if bold:
                format.setFontWeight(QFont.Bold)
            format.setFontItalic(italic)
            cls.Formats[name] = format
Ejemplo n.º 43
0
def syntax_text_char_format(*args):
    ans = QTextCharFormat(*args)
    ans.setProperty(SYNTAX_PROPERTY, True)
    return ans