Skip to content

Parse VT100 ECMA-48 Control Strings: DCS, APC, PM, SOS - #644

Merged
basil merged 4 commits into
lxqt:masterfrom
jquast:jq/bugfix-bad-ansis
May 22, 2026
Merged

basil merged 4 commits into
lxqt:masterfrom
jquast:jq/bugfix-bad-ansis

Conversation

@jquast

@jquast jquast commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

QTerminal echoes raw bytes of unrecognized but valid ECMA-48 Control escape sequences (DCS, APC, PM, SOS) to the screen instead of silently consuming them.

For example, XTGETTCAP queries are visible, which may be used by TUI/CLI apps to determine colors/24-bit color support, OSC 52 clipboard, underline, keyboard sequences, etc.

These are meant for the terminal emulator, not for display output.

Solution

  • Add 'P' (DCS), '_' (APC), '^' (PM), and 'X' (SOS) to the GRP character class so they enter string mode
  • Extend the Xpe macro to recognize all five string initiators.
  • Guard processWindowAttributeChange() (OSC title/attribute handler) so it only fires for OSC strings; non-OSC strings are silently discarded.

Testing

Here is a demonstration script, and its before and after output::

  #!/bin/bash
  # Tests for ECMA-48 string sequence handling.
  ESC=$'\x1b'
  ST="${ESC}\\"
  BEL=$'\x07'

  send_seq() {
      # $1 = display label, $2 = initiator char (] P _ ^ X), $3 = payload
      local label="$1" init="$2" data="$3" term
      printf '%-3s: ' "$label"
      for term in ST BEL; do
          local term_str
          case $term in
              ST)  term_str="$ST";;
              BEL) term_str="$BEL";;
          esac
          printf '%s%s%s%s' "$ESC" "$init" "$data" "$term_str"
      done
      echo
  }

  echo "Each sequence is sent twice using both kinds of terminators."
  echo "A correct terminal emulator should display *nothing* after ':',"
  echo ""

  send_seq "OSC" ']' '0;TEST_OSC'
  send_seq "DCS" 'P' '+qTEST_DCS'
  send_seq "APC" '_' 'TEST_APC'
  send_seq "PM " '^' 'TEST_PM'
  send_seq "SOS" 'X' 'TEST_SOS'
qterminal-before-and-after

Details

From https://ecma-international.org/wp-content/uploads/ECMA-48_5th_edition_june_1991.pdf

5.6 Control strings

A control string is a string of bit combinations which may occur in the data stream as a logical entity for
control purposes. A control string consists of an opening delimiter, a command string or a character string,
and a terminating delimiter, the STRING TERMINATOR (ST).

[..]

a) APPLICATION PROGRAM COMMAND (APC)
b) DEVICE CONTROL STRING (DCS)
c) OPERATING SYSTEM COMMAND (OSC)
d) PRIVACY MESSAGE (PM)
e) START OF STRING (SOS)

(OSC already implemented)

These are all described by XTerm as VT100 Mode Controls beginning with ESC,

APC - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Application-Program-Command-functions
DCS - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Device-Control-functions
PM - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Privacy-Message

and SOS as a C1 (8-Bit) Control character,

SOS - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-C1-lparen-8-Bit-rparen-Control-Characters

@jquast jquast changed the title Bugfix for ECMA-48 Control strings Bugfix VT100 ECMA-48 Control Strings (DCS, APC, PM, SOS) May 21, 2026
@jquast jquast changed the title Bugfix VT100 ECMA-48 Control Strings (DCS, APC, PM, SOS) Handle VT100 ECMA-48 Control Strings (DCS, APC, PM, SOS) May 21, 2026
@jquast jquast changed the title Handle VT100 ECMA-48 Control Strings (DCS, APC, PM, SOS) Parse VT100 ECMA-48 Control Strings: DCS, APC, PM, SOS May 21, 2026
@jquast
jquast marked this pull request as ready for review May 21, 2026 16:09
@tsujan

tsujan commented May 21, 2026

Copy link
Copy Markdown
Member

@basil, could you please review this?

@basil basil left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A promising start. This part of the codebase needs a lot more work to support C1 codepoints and CAN/SUB abort, and it would probably benefit from a rewrite to use an explicit parser state machine like modern Konsole, but none of these changes are in scope for this PR.

The current narrowly scoped PR correctly extends the OSC string-consumption path to DCS/APC/PM/SOS, modulo a few issues which should be addressed before merge.

Comment thread lib/Vt102Emulation.cpp Outdated
#define esp( ) (p == 4 && s[3] == ' ')
#define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']')
#define Xpe (tokenBufferPos >= 2 && (tokenBuffer[1] == ']' || tokenBuffer[1] == 'P' || tokenBuffer[1] == '_' || tokenBuffer[1] == '^' || tokenBuffer[1] == 'X'))
#define Xte (Xpe && (cc == 7 || (prevCC == 27 && cc == 92) )) // 27, 92 => "\e\\" (ST, String Terminator)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Xte accepts BEL (0x07) as a terminator for every string type. BEL as a string terminator is an xterm convention valid only for OSC. DCS, APC, PM, and SOS terminate on ST only.

Because this PR routes all five string types through Xte, a DCS/APC/PM/SOS string whose payload contains a 0x07 byte is truncated at the BEL. The post-BEL bytes are printed to the screen and the trailing ESC becomes a stray ST, which is the behavior this PR is trying to eliminate. Some examples would be SOS payloads (ECMA-48 character string permits arbitrary bytes) and DCS passthrough (e.g. tmux ESC P tmux).

The fix is to gate BEL to OSC only. ST would still terminate all five types. BEL inside a non-OSC string would then fall through to the existing if (Xpe) { prevCC = cc; return; } path and be consumed as payload. The tokenBuffer[1] == ']' guard already present in the Xte branch would keep processWindowAttributeChange() OSC-only.

Comment thread lib/Vt102Emulation.cpp Outdated
#define egt( ) (p >= 3 && s[2] == '>')
#define esp( ) (p == 4 && s[3] == ' ')
#define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']')
#define Xpe (tokenBufferPos >= 2 && (tokenBuffer[1] == ']' || tokenBuffer[1] == 'P' || tokenBuffer[1] == '_' || tokenBuffer[1] == '^' || tokenBuffer[1] == 'X'))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This macro name Xpe still describes OSC exclusively, even though Xpe now matches five string initiators.

Comment thread lib/Vt102Emulation.cpp Outdated
Comment on lines 277 to 278

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment was accurate before this PR, when Xpe was defined solely as tokenBuffer[1] == ']'. After this PR, Xpe also matches P (DCS), _ (APC), ^ (PM), and X (SOS). So both the "(aka OSC)" parenthetical and the "ESC]" example now describe only one of the five string types the branch handles.

@tsujan

tsujan commented May 21, 2026

Copy link
Copy Markdown
Member

@basil
Thank you so much for looking into it!

Problem
-------

QTerminal echoes raw bytes of unrecognized but valid ECMA-48 Control
escape sequences (DCS, APC, PM, SOS) to the screen instead of silently
consuming them.

For example, XTGETTCAP queries are visible
https://codeberg.org/dnkl/foot#xtgettcap which may be used by TUI/CLI
apps to determine 24-bit color support, OSC 52 clipboard support,
colored underline, etc. These are meant for the terminal emulator, not
for display output.

Solution
--------

- Add `P` (DCS), `_` (APC), `^` (PM), `X` (SOS) to the `GRP` character
  class so they enter string mode
- Extend the `Xpe` macro to recognize all five string initiators.
- Guard `processWindowAttributeChange()` (OSC title/attribute handler) so it
  only fires for OSC strings; non-OSC strings are silently discarded.

Testing
-------

Here is a demonstration script, and its before and after output::

    #!/bin/bash
    # ECMA-48 string tests
    ESC=$'\x1b'
    ST="${ESC}\\"
    BEL=$'\x07'

    send_seq() {
        # $1 = display label, $2 = initiator char (] P _ ^ X), $3 = payload
        local label="$1" init="$2" data="$3" term
        printf '%-3s: ' "$label"
        for term in ST BEL; do
            local term_str
            case $term in
                ST)  term_str="$ST";;
                BEL) term_str="$BEL";;
            esac
            printf '%s%s%s%s' "$ESC" "$init" "$data" "$term_str"
        done
        echo
    }

    echo "Each sequence is sent twice using both kinds of terminators"
    echo "ST (ESC \\) and BEL (\\x07). If the fix works **nothing** is displayed after ':'"
    echo ""

    send_seq "OSC" ']' '0;TEST_OSC'
    send_seq "DCS" 'P' '+qTEST_DCS'
    send_seq "APC" '_' 'TEST_APC'
    send_seq "PM " '^' 'TEST_PM'
    send_seq "SOS" 'X' 'TEST_SOS'

Details
-------

From https://ecma-international.org/wp-content/uploads/ECMA-48_5th_edition_june_1991.pdf

> 5.6 Control strings
> A control string is a string of bit combinations which may occur in the data stream as a logical entity for
> control purposes. A control string consists of an opening delimiter, a command string or a character string,
> and a terminating delimiter, the STRING TERMINATOR (ST).
>
> [..]
>
> a) APPLICATION PROGRAM COMMAND (APC)
> b) DEVICE CONTROL STRING (DCS)
> c) OPERATING SYSTEM COMMAND (OSC)
> d) PRIVACY MESSAGE (PM)
> e) START OF STRING (SOS)

(OSC already implemented)

These are all described by XTerm as VT100 Mode Controls beginning with ESC,

APC - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Application-Program-Command-functions
DCS - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Device-Control-functions
PM - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Privacy-Message

and SOS as a C1 (8-Bit) Control character,

SOS - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-C1-lparen-8-Bit-rparen-Control-Characters
@jquast
jquast force-pushed the jq/bugfix-bad-ansis branch from 93a3d63 to 6445b19 Compare May 21, 2026 19:31
@jquast
jquast force-pushed the jq/bugfix-bad-ansis branch from 6445b19 to 6a2da8f Compare May 21, 2026 19:59
@jquast

jquast commented May 21, 2026

Copy link
Copy Markdown
Contributor Author

I've addressed feedback @basil,

I've also done further research on terminating sequences, with testing of the following script of missing ending terminators until reset. On HEAD, this script appears to "lock up" the terminal until/unless a BEL is emitted, fixed by 6a2da8f. This matches Konsole's behavior to reset/clear on ESC in intermediary bytes

#!/bin/sh
printf '\x1bP+DCS-NO-TERM '
printf '\x1b_APC-NO-TERM '
printf '\x1b]0;OSC-NO-TERM '
printf '\x1b^PM-NO-TERM '
printf '\x1bXSOS-NO-TERM '
echo 'FROZEN -- terminal parser is stuck in string mode'
printf '\033c'
echo 'ATTEMPTED RESET -- Welcome back, you should see this!'

Screenshots:

before,
qterminal-before2

after,
qterminal-after2

@basil

basil commented May 21, 2026

Copy link
Copy Markdown
Member

The Xpe naming feedback is still unaddressed. Xte now gates BEL to OSC only, which is good, but the new if (cc == ESC) resetTokenizer(); path inside if (Xpe) prevents ESC \ from being recognized as ST. resetTokenizer() clears prevCC, so the next \ cannot satisfy prevCC == 27 && cc == 92, which means ST termination is probably broken for the control strings, and probably also breaks OSC title changes terminated with ESC \.

can't seem fix the parser from crashing without a major refactor
@jquast

jquast commented May 21, 2026

Copy link
Copy Markdown
Contributor Author

I tried my best @basil, 2fa15b5

I am not able to determine any fix of a "locked up" parser as demonstrated, I guess that's a known limitation of design

before,
after3

after,
qterminal-after3

@jquast

jquast commented May 21, 2026

Copy link
Copy Markdown
Contributor Author

Also, I'm not sure if you're suggesting Xpe is named wrong, I'm not sure what Xpe is meant to represent, so I cannot suggest to rename it, please suggest any renames directly

@basil

basil commented May 21, 2026

Copy link
Copy Markdown
Member

The ST regression I described is fixed in this code. The remaining issue I still see is only the stale Xpe macro name. I think Xpe originally meant something like "Xterm parameter escape". That is not documented, but the evidence points that way:

  • The nearby token comment calls this path XTE_HA ("Xterm window/terminal attribute commands").
  • processWindowAttributeChange() parses the numeric {Pn} parameter from the OSC payload.

That name made sense while Xpe only matched ESC ], because this was specifically the OSC title/window-attribute path. After this PR, Xpe also matches DCS/APC/PM/SOS. Those are ECMA-48 control strings, not xterm window-attribute parameter escapes, and
they do not all have the OSC {Pn};{Text} structure. So the old name is now misleading.

To keep the local three-letter macro style, I'd rename:

  • Xpe -> Cse (control string escape)
  • Xte -> Cte (control string terminator)

That keeps the existing compact style while making the broadened behavior explicit.

@jquast

jquast commented May 22, 2026

Copy link
Copy Markdown
Contributor Author

Renamed as requested 310c311

@basil

basil commented May 22, 2026

Copy link
Copy Markdown
Member

Thanks! LGTM

@tsujan

tsujan commented May 22, 2026

Copy link
Copy Markdown
Member

@basil
If you find its final form satisfying and have tested it, please feel free to merge it.

And welcome to LXQt as a member!

@basil basil left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested this locally and can confirm that this PR correctly makes DCS, APC, PM, and SOS behave like control strings for well-formed input.

qtermwidget's existing (bad) behavior of hanging on unterminated OSC now also applies to these newly-recognized string types. While this is a real behavioral change, it is not a new parser bug. Rather, this PR exposes an existing limitation in qtermwidget's tokenizer. Once the tokenizer enters an unterminated control string, reset/abort handling is not robust.

The proper long-term fix is an explicit parser state machine with well-defined handling for ST, CAN, SUB, C1 controls, and reset behavior, but that is outside the scope of this PR. More work remains, but this PR is a net improvement over the status quo. 👍 Thanks!

@basil
basil merged commit adf8cf2 into lxqt:master May 22, 2026
@jquast
jquast deleted the jq/bugfix-bad-ansis branch May 23, 2026 15:26
Rahelio pushed a commit to Rahelio/qmltermwidget that referenced this pull request Nov 17, 2026
qtermwidget only treated OSC as an ECMA-48 control string. Other valid
string types (DCS, APC, PM, and SOS) were parsed as ordinary escape
sequences, causing their payload bytes to leak onto the terminal display.
This is visible with sequences such as XTGETTCAP, which terminal
applications may use to query capabilities like true color, OSC 52
clipboard support, or underline styling.

Extend the existing control-string handling path to recognize DCS, APC,
PM, and SOS in addition to OSC. ST terminates all five string types, while
BEL remains an OSC-only terminator. The OSC title/window-attribute handler
is still guarded so it only runs for OSC; other control strings are
consumed silently.

This keeps qtermwidget's existing tokenizer model. Unterminated control
strings can still leave the parser stuck until a valid terminator is seen;
that limitation already existed for OSC and needs a separate parser-state
refactor to fix properly.

(cherry picked from commit adf8cf2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Improvements

Development

Successfully merging this pull request may close these issues.

3 participants