• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

jupyter / qtconsole / 10000143105

18 Jul 2024 11:41PM UTC coverage: 61.753% (-0.07%) from 61.826%
10000143105

push

github

web-flow
Merge pull request #611 from jsbautista/boldfacedTextOutputYellow

PR: Change ANSI color code 3 mapping from `brown` to `gold` and set bold format processing enabled by default

1 of 1 new or added line in 1 file covered. (100.0%)

3 existing lines in 2 files now uncovered.

2895 of 4688 relevant lines covered (61.75%)

1.23 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.76
/qtconsole/ansi_code_processor.py
1
""" Utilities for processing ANSI escape codes and special ASCII characters.
2
"""
3
#-----------------------------------------------------------------------------
4
# Imports
5
#-----------------------------------------------------------------------------
6

7
# Standard library imports
8
from collections import namedtuple
2✔
9
import re
2✔
10

11
# System library imports
12
from qtpy import QtGui
2✔
13

14
# Local imports
15
from qtconsole.styles import dark_style
2✔
16

17
#-----------------------------------------------------------------------------
18
# Constants and datatypes
19
#-----------------------------------------------------------------------------
20

21
# An action for erase requests (ED and EL commands).
22
EraseAction = namedtuple('EraseAction', ['action', 'area', 'erase_to'])
2✔
23

24
# An action for cursor move requests (CUU, CUD, CUF, CUB, CNL, CPL, CHA, CUP,
25
# and HVP commands).
26
# FIXME: Not implemented in AnsiCodeProcessor.
27
MoveAction = namedtuple('MoveAction', ['action', 'dir', 'unit', 'count'])
2✔
28

29
# An action for scroll requests (SU and ST) and form feeds.
30
ScrollAction = namedtuple('ScrollAction', ['action', 'dir', 'unit', 'count'])
2✔
31

32
# An action for the carriage return character
33
CarriageReturnAction = namedtuple('CarriageReturnAction', ['action'])
2✔
34

35
# An action for the \n character
36
NewLineAction = namedtuple('NewLineAction', ['action'])
2✔
37

38
# An action for the beep character
39
BeepAction = namedtuple('BeepAction', ['action'])
2✔
40

41
# An action for backspace
42
BackSpaceAction = namedtuple('BackSpaceAction', ['action'])
2✔
43

44
# Regular expressions.
45
CSI_COMMANDS = 'ABCDEFGHJKSTfmnsu'
2✔
46
CSI_SUBPATTERN = '\\[(.*?)([%s])' % CSI_COMMANDS
2✔
47
OSC_SUBPATTERN = '\\](.*?)[\x07\x1b]'
2✔
48
ANSI_PATTERN = ('\x01?\x1b(%s|%s)\x02?' % \
2✔
49
                (CSI_SUBPATTERN, OSC_SUBPATTERN))
50
ANSI_OR_SPECIAL_PATTERN = re.compile('(\a|\b|\r(?!\n)|\r?\n)|(?:%s)' % ANSI_PATTERN)
2✔
51
SPECIAL_PATTERN = re.compile('([\f])')
2✔
52

53
#-----------------------------------------------------------------------------
54
# Classes
55
#-----------------------------------------------------------------------------
56

57
class AnsiCodeProcessor(object):
2✔
58
    """ Translates special ASCII characters and ANSI escape codes into readable
59
        attributes. It also supports a few non-standard, xterm-specific codes.
60
    """
61

62
    # Whether to increase intensity or set boldness for SGR code 1.
63
    # (Different terminals handle this in different ways.)
64
    bold_text_enabled = True
2✔
65

66
    # We provide an empty default color map because subclasses will likely want
67
    # to use a custom color format.
68
    default_color_map = {}
2✔
69

70
    #---------------------------------------------------------------------------
71
    # AnsiCodeProcessor interface
72
    #---------------------------------------------------------------------------
73

74
    def __init__(self):
2✔
75
        self.actions = []
2✔
76
        self.color_map = self.default_color_map.copy()
2✔
77
        self.reset_sgr()
2✔
78

79
    def reset_sgr(self):
2✔
80
        """ Reset graphics attributs to their default values.
81
        """
82
        self.intensity = 0
2✔
83
        self.italic = False
2✔
84
        self.bold = False
2✔
85
        self.underline = False
2✔
86
        self.foreground_color = None
2✔
87
        self.background_color = None
2✔
88

89
    def split_string(self, string):
2✔
90
        """ Yields substrings for which the same escape code applies.
91
        """
92
        self.actions = []
2✔
93
        start = 0
2✔
94

95
        # strings ending with \r are assumed to be ending in \r\n since
96
        # \n is appended to output strings automatically.  Accounting
97
        # for that, here.
98
        last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None
2✔
99
        string = string[:-1] if last_char is not None else string
2✔
100

101
        for match in ANSI_OR_SPECIAL_PATTERN.finditer(string):
2✔
102
            raw = string[start:match.start()]
2✔
103
            substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
2✔
104
            if substring or self.actions:
2✔
105
                yield substring
2✔
106
                self.actions = []
2✔
107
            start = match.end()
2✔
108

109
            groups = [g for g in match.groups() if (g is not None)]
2✔
110
            g0 = groups[0]
2✔
111
            if g0 == '\a':
2✔
112
                self.actions.append(BeepAction('beep'))
2✔
113
                yield None
2✔
114
                self.actions = []
2✔
115
            elif g0 == '\r':
2✔
116
                self.actions.append(CarriageReturnAction('carriage-return'))
2✔
117
                yield None
2✔
118
                self.actions = []
2✔
119
            elif g0 == '\b':
2✔
120
                self.actions.append(BackSpaceAction('backspace'))
2✔
121
                yield None
2✔
122
                self.actions = []
2✔
123
            elif g0 == '\n' or g0 == '\r\n':
2✔
124
                self.actions.append(NewLineAction('newline'))
2✔
125
                yield g0
2✔
126
                self.actions = []
2✔
127
            else:
128
                params = [ param for param in groups[1].split(';') if param ]
2✔
129
                if g0.startswith('['):
2✔
130
                    # Case 1: CSI code.
131
                    try:
2✔
132
                        params = list(map(int, params))
2✔
133
                    except ValueError:
×
134
                        # Silently discard badly formed codes.
135
                        pass
×
136
                    else:
137
                        self.set_csi_code(groups[2], params)
2✔
138

139
                elif g0.startswith(']'):
2✔
140
                    # Case 2: OSC code.
141
                    self.set_osc_code(params)
2✔
142

143
        raw = string[start:]
2✔
144
        substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
2✔
145
        if substring or self.actions:
2✔
146
            yield substring
2✔
147

148
        if last_char is not None:
2✔
149
            self.actions.append(NewLineAction('newline'))
2✔
150
            yield last_char
2✔
151

152
    def set_csi_code(self, command, params=[]):
2✔
153
        """ Set attributes based on CSI (Control Sequence Introducer) code.
154

155
        Parameters
156
        ----------
157
        command : str
158
            The code identifier, i.e. the final character in the sequence.
159

160
        params : sequence of integers, optional
161
            The parameter codes for the command.
162
        """
163
        if command == 'm':   # SGR - Select Graphic Rendition
2✔
164
            if params:
2✔
165
                self.set_sgr_code(params)
2✔
166
            else:
167
                self.set_sgr_code([0])
×
168

169
        elif (command == 'J' or # ED - Erase Data
2✔
170
              command == 'K'):  # EL - Erase in Line
171
            code = params[0] if params else 0
2✔
172
            if 0 <= code <= 2:
2✔
173
                area = 'screen' if command == 'J' else 'line'
2✔
174
                if code == 0:
2✔
175
                    erase_to = 'end'
2✔
176
                elif code == 1:
2✔
177
                    erase_to = 'start'
2✔
178
                elif code == 2:
2✔
179
                    erase_to = 'all'
2✔
180
                self.actions.append(EraseAction('erase', area, erase_to))
2✔
181

182
        elif (command == 'S' or # SU - Scroll Up
2✔
183
              command == 'T'):  # SD - Scroll Down
184
            dir = 'up' if command == 'S' else 'down'
2✔
185
            count = params[0] if params else 1
2✔
186
            self.actions.append(ScrollAction('scroll', dir, 'line', count))
2✔
187

188
    def set_osc_code(self, params):
2✔
189
        """ Set attributes based on OSC (Operating System Command) parameters.
190

191
        Parameters
192
        ----------
193
        params : sequence of str
194
            The parameters for the command.
195
        """
196
        try:
2✔
197
            command = int(params.pop(0))
2✔
198
        except (IndexError, ValueError):
×
199
            return
×
200

201
        if command == 4:
2✔
202
            # xterm-specific: set color number to color spec.
203
            try:
2✔
204
                color = int(params.pop(0))
2✔
205
                spec = params.pop(0)
2✔
206
                self.color_map[color] = self._parse_xterm_color_spec(spec)
2✔
207
            except (IndexError, ValueError):
×
208
                pass
×
209

210
    def set_sgr_code(self, params):
2✔
211
        """ Set attributes based on SGR (Select Graphic Rendition) codes.
212

213
        Parameters
214
        ----------
215
        params : sequence of ints
216
            A list of SGR codes for one or more SGR commands. Usually this
217
            sequence will have one element per command, although certain
218
            xterm-specific commands requires multiple elements.
219
        """
220
        # Always consume the first parameter.
221
        if not params:
2✔
222
            return
2✔
223
        code = params.pop(0)
2✔
224

225
        if code == 0:
2✔
226
            self.reset_sgr()
2✔
227
        elif code == 1:
2✔
228
            if self.bold_text_enabled:
2✔
229
                self.bold = True
2✔
230
            else:
UNCOV
231
                self.intensity = 1
×
232
        elif code == 2:
2✔
233
            self.intensity = 0
×
234
        elif code == 3:
2✔
235
            self.italic = True
×
236
        elif code == 4:
2✔
237
            self.underline = True
×
238
        elif code == 22:
2✔
239
            self.intensity = 0
×
240
            self.bold = False
×
241
        elif code == 23:
2✔
242
            self.italic = False
×
243
        elif code == 24:
2✔
244
            self.underline = False
×
245
        elif code >= 30 and code <= 37:
2✔
246
            self.foreground_color = code - 30
2✔
247
        elif code == 38 and params:
2✔
248
            _color_type = params.pop(0)
2✔
249
            if _color_type == 5 and params:
2✔
250
                # xterm-specific: 256 color support.
251
                self.foreground_color = params.pop(0)
2✔
252
            elif _color_type == 2:
2✔
253
                # 24bit true colour support.
254
                self.foreground_color = params[:3]
2✔
255
                params[:3] = []
2✔
256
        elif code == 39:
2✔
257
            self.foreground_color = None
2✔
258
        elif code >= 40 and code <= 47:
2✔
259
            self.background_color = code - 40
2✔
260
        elif code == 48 and params:
2✔
261
            _color_type = params.pop(0)
2✔
262
            if _color_type == 5 and params:
2✔
263
                # xterm-specific: 256 color support.
264
                self.background_color = params.pop(0)
2✔
265
            elif _color_type == 2:
2✔
266
                # 24bit true colour support.
267
                self.background_color = params[:3]
2✔
268
                params[:3] = []
2✔
269
        elif code == 49:
2✔
270
            self.background_color = None
2✔
271

272
        # Recurse with unconsumed parameters.
273
        self.set_sgr_code(params)
2✔
274

275
    #---------------------------------------------------------------------------
276
    # Protected interface
277
    #---------------------------------------------------------------------------
278

279
    def _parse_xterm_color_spec(self, spec):
2✔
280
        if spec.startswith('rgb:'):
2✔
281
            return tuple(map(lambda x: int(x, 16), spec[4:].split('/')))
2✔
282
        elif spec.startswith('rgbi:'):
2✔
283
            return tuple(map(lambda x: int(float(x) * 255),
2✔
284
                             spec[5:].split('/')))
285
        elif spec == '?':
×
286
            raise ValueError('Unsupported xterm color spec')
×
287
        return spec
×
288

289
    def _replace_special(self, match):
2✔
290
        special = match.group(1)
2✔
291
        if special == '\f':
2✔
292
            self.actions.append(ScrollAction('scroll', 'down', 'page', 1))
2✔
293
        return ''
2✔
294

295

296
class QtAnsiCodeProcessor(AnsiCodeProcessor):
2✔
297
    """ Translates ANSI escape codes into QTextCharFormats.
298
    """
299

300
    # A map from ANSI color codes to SVG color names or RGB(A) tuples.
301
    darkbg_color_map = {
2✔
302
        0  : 'black',       # black
303
        1  : 'darkred',     # red
304
        2  : 'darkgreen',   # green
305
        3  : 'gold',       # yellow
306
        4  : 'darkblue',    # blue
307
        5  : 'darkviolet',  # magenta
308
        6  : 'steelblue',   # cyan
309
        7  : 'grey',        # white
310
        8  : 'grey',        # black (bright)
311
        9  : 'red',         # red (bright)
312
        10 : 'lime',        # green (bright)
313
        11 : 'yellow',      # yellow (bright)
314
        12 : 'deepskyblue', # blue (bright)
315
        13 : 'magenta',     # magenta (bright)
316
        14 : 'cyan',        # cyan (bright)
317
        15 : 'white' }      # white (bright)
318

319
    # Set the default color map for super class.
320
    default_color_map = darkbg_color_map.copy()
2✔
321

322
    def get_color(self, color, intensity=0):
2✔
323
        """ Returns a QColor for a given color code or rgb list, or None if one
324
            cannot be constructed.
325
        """
326

327
        if isinstance(color, int):
2✔
328
            # Adjust for intensity, if possible.
329
            if color < 8 and intensity > 0:
2✔
UNCOV
330
                color += 8
×
331
            constructor = self.color_map.get(color, None)
2✔
332
        elif isinstance(color, (tuple, list)):
2✔
333
            constructor = color
×
334
        else:
335
            return None
2✔
336

337
        if isinstance(constructor, str):
2✔
338
            # If this is an X11 color name, we just hope there is a close SVG
339
            # color name. We could use QColor's static method
340
            # 'setAllowX11ColorNames()', but this is global and only available
341
            # on X11. It seems cleaner to aim for uniformity of behavior.
342
            return QtGui.QColor(constructor)
2✔
343

344
        elif isinstance(constructor, (tuple, list)):
2✔
345
            return QtGui.QColor(*constructor)
×
346

347
        return None
2✔
348

349
    def get_format(self):
2✔
350
        """ Returns a QTextCharFormat that encodes the current style attributes.
351
        """
352
        format = QtGui.QTextCharFormat()
2✔
353

354
        # Set foreground color
355
        qcolor = self.get_color(self.foreground_color, self.intensity)
2✔
356
        if qcolor is not None:
2✔
357
            format.setForeground(qcolor)
2✔
358

359
        # Set background color
360
        qcolor = self.get_color(self.background_color, self.intensity)
2✔
361
        if qcolor is not None:
2✔
362
            format.setBackground(qcolor)
2✔
363

364
        # Set font weight/style options
365
        if self.bold:
2✔
366
            format.setFontWeight(QtGui.QFont.Bold)
2✔
367
        else:
368
            format.setFontWeight(QtGui.QFont.Normal)
2✔
369
        format.setFontItalic(self.italic)
2✔
370
        format.setFontUnderline(self.underline)
2✔
371

372
        return format
2✔
373

374
    def set_background_color(self, style):
2✔
375
        """
376
        Given a syntax style, attempt to set a color map that will be
377
        aesthetically pleasing.
378
        """
379
        # Set a new default color map.
380
        self.default_color_map = self.darkbg_color_map.copy()
2✔
381

382
        if not dark_style(style):
2✔
383
            # Colors appropriate for a terminal with a light background. For
384
            # now, only use non-bright colors...
385
            for i in range(8):
2✔
386
                self.default_color_map[i + 8] = self.default_color_map[i]
2✔
387

388
            # ...and replace white with black.
389
            self.default_color_map[7] = self.default_color_map[15] = 'black'
2✔
390

391
        # Update the current color map with the new defaults.
392
        self.color_map.update(self.default_color_map)
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc