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

spyder-ide / qtconsole / 21851323698

10 Feb 2026 04:08AM UTC coverage: 61.508% (-0.02%) from 61.53%
21851323698

Pull #650

github

web-flow
Merge 5c652c31d into e8b3dc94c
Pull Request #650: PR: Add ansi code to hide cursor

3 of 6 new or added lines in 1 file covered. (50.0%)

3 existing lines in 1 file now uncovered.

2937 of 4775 relevant lines covered (61.51%)

1.84 hits per line

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

87.7
/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
3✔
9
import re
3✔
10

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

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

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

21
# An action for cursor visibility requests
22
CursorVisibilityAction = namedtuple('CursorVisibilityAction', ['action', 'visible'])
3✔
23

24
# An action for erase requests (ED and EL commands).
25
EraseAction = namedtuple('EraseAction', ['action', 'area', 'erase_to'])
3✔
26

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

32
# An action for scroll requests (SU and ST) and form feeds.
33
ScrollAction = namedtuple('ScrollAction', ['action', 'dir', 'unit', 'count'])
3✔
34

35
# An action for the carriage return character
36
CarriageReturnAction = namedtuple('CarriageReturnAction', ['action'])
3✔
37

38
# An action for the \n character
39
NewLineAction = namedtuple('NewLineAction', ['action'])
3✔
40

41
# An action for the beep character
42
BeepAction = namedtuple('BeepAction', ['action'])
3✔
43

44
# An action for backspace
45
BackSpaceAction = namedtuple('BackSpaceAction', ['action'])
3✔
46

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

56
#-----------------------------------------------------------------------------
57
# Classes
58
#-----------------------------------------------------------------------------
59

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

65
    # Whether to increase intensity or set boldness for SGR code 1.
66
    # (Different terminals handle this in different ways.)
67
    bold_text_enabled = True
3✔
68

69
    # We provide an empty default color map because subclasses will likely want
70
    # to use a custom color format.
71
    default_color_map = {}
3✔
72

73
    #---------------------------------------------------------------------------
74
    # AnsiCodeProcessor interface
75
    #---------------------------------------------------------------------------
76

77
    def __init__(self):
3✔
78
        self.actions = []
3✔
79
        self.color_map = self.default_color_map.copy()
3✔
80
        self.reset_sgr()
3✔
81

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

92
    def split_string(self, string):
3✔
93
        """ Yields substrings for which the same escape code applies.
94
        """
95
        self.actions = []
3✔
96
        start = 0
3✔
97

98
        last_char = None
3✔
99
        string = string[:-1] if last_char is not None else string
3✔
100

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

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

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

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

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

152
    def set_csi_code(self, command, params=[]):
3✔
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

164
        if command in ('h', 'l'):
3✔
NEW
165
            if params == [25]:
×
NEW
166
                visible = (command == 'h')
×
NEW
167
                self.actions.append(
×
168
                    CursorVisibilityAction('cursor-visibility', visible)
169
                )
170
        if command == 'm':   # SGR - Select Graphic Rendition
3✔
171
            if params:
3✔
172
                self.set_sgr_code(params)
3✔
173
            else:
174
                self.set_sgr_code([0])
×
175

176
        elif (command == 'J' or # ED - Erase Data
3✔
177
              command == 'K'):  # EL - Erase in Line
178
            code = params[0] if params else 0
3✔
179
            if 0 <= code <= 2:
3✔
180
                area = 'screen' if command == 'J' else 'line'
3✔
181
                if code == 0:
3✔
182
                    erase_to = 'end'
3✔
183
                elif code == 1:
3✔
184
                    erase_to = 'start'
3✔
185
                elif code == 2:
3✔
186
                    erase_to = 'all'
3✔
187
                self.actions.append(EraseAction('erase', area, erase_to))
3✔
188

189
        elif (command == 'S' or # SU - Scroll Up
3✔
190
              command == 'T'):  # SD - Scroll Down
191
            dir = 'up' if command == 'S' else 'down'
3✔
192
            count = params[0] if params else 1
3✔
193
            self.actions.append(ScrollAction('scroll', dir, 'line', count))
3✔
194

195
        elif command == 'A':  # Move N lines Up
3✔
196
            dir = 'up'
3✔
197
            count = params[0] if params else 1
3✔
198
            self.actions.append(MoveAction('move', dir, 'line', count))
3✔
199

200
        elif command == 'B':  # Move N lines Down
3✔
201
            dir = 'down'
×
202
            count = params[0] if params else 1
×
203
            self.actions.append(MoveAction('move', dir, 'line', count))
×
204

205
        elif command == 'F':  # Goes back to the begining of the n-th previous line
3✔
206
            dir = 'leftup'
3✔
207
            count = params[0] if params else 1
3✔
208
            self.actions.append(MoveAction('move', dir, 'line', count))
3✔
209
        
210

211
    def set_osc_code(self, params):
3✔
212
        """ Set attributes based on OSC (Operating System Command) parameters.
213

214
        Parameters
215
        ----------
216
        params : sequence of str
217
            The parameters for the command.
218
        """
219
        try:
3✔
220
            command = int(params.pop(0))
3✔
221
        except (IndexError, ValueError):
×
222
            return
×
223

224
        if command == 4:
3✔
225
            # xterm-specific: set color number to color spec.
226
            try:
3✔
227
                color = int(params.pop(0))
3✔
228
                spec = params.pop(0)
3✔
229
                self.color_map[color] = self._parse_xterm_color_spec(spec)
3✔
230
            except (IndexError, ValueError):
×
231
                pass
×
232

233
    def set_sgr_code(self, params):
3✔
234
        """ Set attributes based on SGR (Select Graphic Rendition) codes.
235

236
        Parameters
237
        ----------
238
        params : sequence of ints
239
            A list of SGR codes for one or more SGR commands. Usually this
240
            sequence will have one element per command, although certain
241
            xterm-specific commands requires multiple elements.
242
        """
243
        # Always consume the first parameter.
244
        if not params:
3✔
245
            return
3✔
246
        code = params.pop(0)
3✔
247

248
        if code == 0:
3✔
249
            self.reset_sgr()
3✔
250
        elif code == 1:
3✔
251
            if self.bold_text_enabled:
3✔
252
                self.bold = True
3✔
253
            else:
254
                self.intensity = 1
×
255
        elif code == 2:
3✔
256
            self.intensity = 0
×
257
        elif code == 3:
3✔
UNCOV
258
            self.italic = True
1✔
259
        elif code == 4:
3✔
260
            self.underline = True
×
261
        elif code == 22:
3✔
262
            self.intensity = 0
×
263
            self.bold = False
×
264
        elif code == 23:
3✔
265
            self.italic = False
×
266
        elif code == 24:
3✔
267
            self.underline = False
×
268
        elif code >= 30 and code <= 37:
3✔
269
            self.foreground_color = code - 30
3✔
270
        elif code == 38 and params:
3✔
271
            _color_type = params.pop(0)
3✔
272
            if _color_type == 5 and params:
3✔
273
                # xterm-specific: 256 color support.
274
                self.foreground_color = params.pop(0)
3✔
275
            elif _color_type == 2:
3✔
276
                # 24bit true colour support.
277
                self.foreground_color = params[:3]
3✔
278
                params[:3] = []
3✔
279
        elif code == 39:
3✔
280
            self.foreground_color = None
3✔
281
        elif code >= 40 and code <= 47:
3✔
282
            self.background_color = code - 40
3✔
283
        elif code == 48 and params:
3✔
284
            _color_type = params.pop(0)
3✔
285
            if _color_type == 5 and params:
3✔
286
                # xterm-specific: 256 color support.
287
                self.background_color = params.pop(0)
3✔
288
            elif _color_type == 2:
3✔
289
                # 24bit true colour support.
290
                self.background_color = params[:3]
3✔
291
                params[:3] = []
3✔
292
        elif code == 49:
3✔
293
            self.background_color = None
3✔
294
        elif code >= 90 and code <= 97:
3✔
295
            # Bright foreground color
296
            self.foreground_color = code - 90
3✔
297
            self.intensity = 1
3✔
298
        elif code >=100 and code <= 107:
×
299
            # Bright background color
300
            self.background_color = code - 100
×
301
            self.intensity = 1
×
302

303
        # Recurse with unconsumed parameters.
304
        self.set_sgr_code(params)
3✔
305

306
    #---------------------------------------------------------------------------
307
    # Protected interface
308
    #---------------------------------------------------------------------------
309

310
    def _parse_xterm_color_spec(self, spec):
3✔
311
        if spec.startswith('rgb:'):
3✔
312
            return tuple(map(lambda x: int(x, 16), spec[4:].split('/')))
3✔
313
        elif spec.startswith('rgbi:'):
3✔
314
            return tuple(map(lambda x: int(float(x) * 255),
3✔
315
                             spec[5:].split('/')))
316
        elif spec == '?':
×
317
            raise ValueError('Unsupported xterm color spec')
×
318
        return spec
×
319

320
    def _replace_special(self, match):
3✔
321
        special = match.group(1)
3✔
322
        if special == '\f':
3✔
323
            self.actions.append(ScrollAction('scroll', 'down', 'page', 1))
3✔
324
        return ''
3✔
325

326
    def _parse_ansi_color(self, color, intensity):
3✔
327
        """
328
        Map an ANSI color code to color name or a RGB tuple.
329
        Based on: https://gist.github.com/MightyPork/1d9bd3a3fd4eb1a661011560f6921b5b
330
        """
331
        parsed_color = None
3✔
332
        if color < 16:
3✔
333
            # Adjust for intensity, if possible.
334
            if intensity > 0 and color < 8:
3✔
335
                color += 8
3✔
336
            parsed_color = self.color_map.get(color, None)
3✔
337
        elif (color > 231):
3✔
UNCOV
338
                s = int((color - 232) * 10 + 8)
1✔
UNCOV
339
                parsed_color = (s, s, s)
1✔
340
        else:
341
            n = color - 16
3✔
342
            b = n % 6
3✔
343
            g = (n - b) / 6 % 6
3✔
344
            r = (n - b - g * 6) / 36 % 6
3✔
345
            r = int(r * 40 + 55) if r else 0
3✔
346
            g = int(g * 40 + 55) if g else 0
3✔
347
            b = int(b * 40 + 55) if b else 0
3✔
348
            parsed_color = (r, g, b)
3✔
349
        return parsed_color
3✔
350

351

352
class QtAnsiCodeProcessor(AnsiCodeProcessor):
3✔
353
    """ Translates ANSI escape codes into QTextCharFormats.
354
    """
355

356
    # A map from ANSI color codes to SVG color names or RGB(A) tuples.
357
    darkbg_color_map = {
3✔
358
        0  : 'black',       # black
359
        1  : 'darkred',     # red
360
        2  : 'darkgreen',   # green
361
        3  : 'gold',       # yellow
362
        4  : 'darkblue',    # blue
363
        5  : 'darkviolet',  # magenta
364
        6  : 'steelblue',   # cyan
365
        7  : 'grey',        # white
366
        8  : 'grey',        # black (bright)
367
        9  : 'red',         # red (bright)
368
        10 : 'lime',        # green (bright)
369
        11 : 'yellow',      # yellow (bright)
370
        12 : 'deepskyblue', # blue (bright)
371
        13 : 'magenta',     # magenta (bright)
372
        14 : 'cyan',        # cyan (bright)
373
        15 : 'white' }      # white (bright)
374

375
    # Set the default color map for super class.
376
    default_color_map = darkbg_color_map.copy()
3✔
377

378
    def get_color(self, color, intensity=0):
3✔
379
        """ Returns a QColor for a given color code or rgb list, or None if one
380
            cannot be constructed.
381
        """
382
        if isinstance(color, int):
3✔
383
            constructor = self._parse_ansi_color(color, intensity)
3✔
384
        elif isinstance(color, (tuple, list)):
3✔
385
            constructor = color
×
386
        else:
387
            return None
3✔
388

389
        if isinstance(constructor, str):
3✔
390
            # If this is an X11 color name, we just hope there is a close SVG
391
            # color name. We could use QColor's static method
392
            # 'setAllowX11ColorNames()', but this is global and only available
393
            # on X11. It seems cleaner to aim for uniformity of behavior.
394
            return QtGui.QColor(constructor)
3✔
395

396
        elif isinstance(constructor, (tuple, list)):
3✔
397
            return QtGui.QColor(*constructor)
3✔
398

399
        return None
×
400

401
    def get_format(self):
3✔
402
        """ Returns a QTextCharFormat that encodes the current style attributes.
403
        """
404
        format = QtGui.QTextCharFormat()
3✔
405

406
        # Set foreground color
407
        qcolor = self.get_color(self.foreground_color, self.intensity)
3✔
408
        if qcolor is not None:
3✔
409
            format.setForeground(qcolor)
3✔
410

411
        # Set background color
412
        qcolor = self.get_color(self.background_color, self.intensity)
3✔
413
        if qcolor is not None:
3✔
414
            format.setBackground(qcolor)
3✔
415

416
        # Set font weight/style options
417
        if self.bold:
3✔
418
            format.setFontWeight(QtGui.QFont.Bold)
3✔
419
        else:
420
            format.setFontWeight(QtGui.QFont.Normal)
3✔
421
        format.setFontItalic(self.italic)
3✔
422
        format.setFontUnderline(self.underline)
3✔
423

424
        return format
3✔
425

426
    def set_background_color(self, style):
3✔
427
        """
428
        Given a syntax style, attempt to set a color map that will be
429
        aesthetically pleasing.
430
        """
431
        # Set a new default color map.
432
        self.default_color_map = self.darkbg_color_map.copy()
3✔
433

434
        if not dark_style(style):
3✔
435
            # Colors appropriate for a terminal with a light background. For
436
            # now, only use non-bright colors...
437
            for i in range(8):
3✔
438
                self.default_color_map[i + 8] = self.default_color_map[i]
3✔
439

440
            # ...and replace white with black.
441
            self.default_color_map[7] = self.default_color_map[15] = 'black'
3✔
442

443
        # Update the current color map with the new defaults.
444
        self.color_map.update(self.default_color_map)
3✔
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

© 2026 Coveralls, Inc