Skip to content

Light-background flash on startup in dark terminals - #21664

Closed
akasakariko wants to merge 1 commit into
vim:masterfrom
akasakariko:fix/startup-background-21605
Closed

akasakariko wants to merge 1 commit into
vim:masterfrom
akasakariko:fix/startup-background-21605

Conversation

@akasakariko

@akasakariko akasakariko commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Dark terminals can briefly show a light background before Vim receives the terminal background color response

Add 'termbackgroundwait' ('tbw'), defaulting to 0, so users can opt into waiting before the first screen clear
The default keeps terminal queries after startup commands, including no OSC 11 query for vim --clean -c qa

  • Measure the wait using elapsed time where supported, polling at intervals of at most 10 ms and stopping for a response, pending input, or an interrupt
  • Explicitly require a positive wait value, terminal input and output, and neither a running nor starting GUI at the early query call site
  • Preserve typed and redirected input, consume OSC notifications at interactive prompts, and restore terminal input mode and colors during exit or handoff to child commands
  • Update colors immediately while deferring background and OSC autocmd redraws until startup finishes
  • Document the option and the background-flash help tag, including the possibility of a flash when a response arrives after the timeout

Related to #21605

Squashed into one commit, 48cf56f, on the existing upstream base 205b06c
The PR contains no CI configuration changes or unrelated diff performance changes

Review verification

exit_scroll() still emits CR-LF in raw mode because out_char() adds the carriage return
The existing handoff test now checks the newline before stoptermcap() with a nonempty t_ti that does not switch screens
Temporarily restoring the earlier cooked-mode transition reproduces the late OSC 11 echo, so pending responses must still be handled before that transition

Local validation on macOS arm64

  • Huge and Tiny builds pass without new warnings
  • Tiny-compatible make test passes
  • Complete startup, termcodes, messages, autocmd, options, options_all, terminal, help, and codestyle suites pass in a PTY with TEST_NO_RETRY=1 — 1023 tests pass and 16 existing platform or feature checks are skipped
  • Six PTY exit scenarios preserve CR-LF, covering alternate-screen, non-swapping t_ti, empty t_ti, Ex mode, help, and version output
  • The preprocessor indentation script produces no changes and git diff --check HEAD^ HEAD passes

The first suite run failed in Test_redirect_Ctrl_C and Test_WinScrolled
Each passes three targeted runs on the updated binary, followed by two passing complete startup and autocmd runs without code changes
The Ctrl-C timeout also reproduces three times on the previous-head binary

Full GUI suites, Windows, ASan, and the full Huge test suite were not run locally

Linux clipboard verification

The earlier Clang run failed in Test_clipmethod_order() with expected x11, actual none, and skipped its coverage upload
Its four startup background tests passed

On Colima with Ubuntu 26.04 arm64 and Clang 21, both this source tree and upstream base 205b06c build successfully
Each passes 20 targeted clipboard-order runs and three complete clipboard suites with TEST_NO_RETRY=1, totaling 70 test executions without skips
The x86_64 Clang 23 CI failure was not reproduced locally

Commit 48cf56f refreshes only commit metadata to trigger another CI run after the upstream rerun API returned HTTP 403
Its source tree is identical to 3a39bd1, preserving the single-commit structure without changing code, assertions, or workflow configuration

GitHub CI for 48cf56f85 has completed, with all 40 PR checks reported successful and none pending
The Linux huge Clang job passes the clipboard-order test, all four startup background tests, and its coverage generation and upload steps
Project coverage is 82.44% against the 82.42% base, and patch coverage is 93.33%

The GTK4 log still times out in Test_cscopeWithCscopeConnections() after 20 minutes, as it did in the previous run
Its successful check status comes from the repository's existing continue-on-error policy and does not establish that the complete GTK4 suite passed

@habamax

habamax commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

So it would 100ms to vim startup for terminals that fail to respond for background query?

And if the response comes late, does it mean the flicker light->dark would still happen in case light was initial state and response is dark?

@akasakariko

Copy link
Copy Markdown
Contributor Author

Yes to both, with some conditions

During interactive startup, if background is unset and Vim sends a background query, an unresponsive terminal can incur the full 100 ms wait
The wait ends early on a response, pending keyboard input, or an interrupt, and is skipped when background is explicitly set or t_RB is empty

A response arriving after the timeout can still cause a light-to-dark flash
This is a bounded wait to avoid the flash when the response arrives in time, rather than a guarantee for late responses

@akasakariko

Copy link
Copy Markdown
Contributor Author

CI retry update

The empty commit a54bf7e retriggers CI with an identical source tree and no changes to tests or coverage thresholds

The original project coverage drop is concentrated in incorrectly attributed mouse.c reports — the 101-line src/libvterm/src/mouse.c has coverage through line 3635, while the Linux uploads attribute only 45–49 lines to Vim’s src/mouse.c

In the retry, codecov/patch passes, but the Clang job fails in Test_clipmethod_order() because StartWaylandCompositor() leaves the display name empty
Both Test_startup_background() and Test_term_getpos() pass, and the Wayland test passed on the previous commit with the same source tree
The failed job skips coverage generation and upload, so the project coverage report is still incomplete

Could a maintainer rerun the Linux huge Clang job?
The rerun API returns HTTP 403, requiring repository admin rights
The original coverage failure is not yet resolved, and the shared report-path issue may still need a separate fix

@github-actions github-actions Bot added the CI GHA, Cirrus, AppVeyor, ... label Oct 29, 2026
@akasakariko
akasakariko force-pushed the fix/startup-background-21605 branch from b7912af to e42c079 Compare October 29, 2026 01:03
@habamax

habamax commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

During interactive startup, if background is unset and Vim sends a background query, an unresponsive terminal can incur the full 100 ms wait

This would generate quite a few issues here.

A response arriving after the timeout can still cause a light-to-dark flash

We already had that. The patch was reverted in the end due to multiple issues raised, as far as I remember.

@akasakariko

akasakariko commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed e42c079

  • Fixed ambiguous gcov source paths by generating reports in each compilation directory and making Source paths absolute
  • Disabled Codecov gcov regeneration while retaining all generated reports
  • Made the startup background test independent of the parent terminal palette by saving, enabling, and restoring termguicolors

Verified locally with GCC and Clang coverage reproductions, the actual Codecov gcov plugin, the startup and terminal position regressions, all clipboard and Wayland tests, and libvterm tests

The Linux non-GUI startup suite passed with its existing GUI skips
The GTK window suite passed five consecutive runs of all 82 tests
Broader local checks also exposed container GTK sandbox warnings, a macOS bash shutdown failure, and a terminal suite early exit, so those runs are not claimed as passing

In CI run 40798043666, both Linux GCC and Clang full-test jobs passed, including the previously failing clipboard test
Both codecov/project and codecov/patch now pass

Two new failures remain in unchanged test files

Could a maintainer rerun these two jobs
The rerun API returns HTTP 403 because repository admin rights are required
Neither failure has been bypassed or had its assertions weakened
31 jobs have passed and the GTK4 job is still running
Project coverage is 83.31% against the 83.11% base

@akasakariko

Copy link
Copy Markdown
Contributor Author

I will handle it.

@akasakariko

Copy link
Copy Markdown
Contributor Author

@habamax Thanks for the feedback

I reproduced the 100 ms wait with an unresponsive terminal and a light-to-dark flash when the background response arrived after the timeout
Simply removing the wait makes the existing first-frame regression test fail, so I reverted that experiment and have not pushed a replacement yet

Before revising this PR, which direction would you prefer?

  • Keep startup non-blocking and treat background detection as best-effort, accepting that a late response may still cause a flash
  • Make the startup wait explicitly opt-in, with no added wait by default

If neither approach is appropriate, what alternative would you recommend?
Could you also share a reference to the previously reverted patch, if you remember it, so I can investigate the issues it caused?

@habamax

habamax commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Before revising this PR, which direction would you prefer?

* Keep startup non-blocking and treat background detection as best-effort, accepting that a late response may still cause a flash

* Make the startup wait explicitly opt-in, with no added wait by default

There definitely shouldn't be an added wait by default, not 100ms at least given that my (and many others) full vim config is loaded under 50ms and bare vim is way less.

If neither approach is appropriate, what alternative would you recommend?

I would go with opt-in configurable wait, but that is for @chrisbra @64-bitman and the team to decide.

Could you also share a reference to the previously reverted patch, if you remember it, so I can investigate the issues it caused?

I can't find it, I just remember there was an email thread in vim.dev about vim unexpectedly changing colors after some time (due to late terminal response to t_RB or something).

@akasakariko

Copy link
Copy Markdown
Contributor Author

Thanks, I will wait for the direction from the team

@64-bitman

Copy link
Copy Markdown
Member

I think we should make the startup wait an option (default no), and update documentation to point users experiencing this problem to that option.

@akasakariko

Copy link
Copy Markdown
Contributor Author

Thanks, I will submit the update this afternoon (Tokyo time)

@akasakariko

Copy link
Copy Markdown
Contributor Author

I have addressed the feedback

@akasakariko
akasakariko force-pushed the fix/startup-background-21605 branch 2 times, most recently from 7277aaf to 1e18739 Compare October 31, 2026 06:07
Comment thread runtime/doc/options.txt Resolved
Comment thread runtime/doc/options.txt Resolved
@akasakariko
akasakariko force-pushed the fix/startup-background-21605 branch from 1e18739 to 7d40247 Compare October 31, 2026 11:02
@akasakariko

akasakariko commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed 61f336c to address the review comments and the shared CI failure

  • Added the background-flash help tag and replaced the repeated option example with a cross-reference
  • Fixed processed OSC notifications remaining in typeahead after startup commands and preventing SafeState from firing
  • Also handle the earlier background response when no foreground query is sent, covered by the existing autocmd test without weakening assertions

Local validation on macOS arm64

  • make -C src -j6 and make -C src/shadow-tiny -j6 pass with no new warnings
  • The original Test_Changed_ChangedI failure reproduced on ten attempts before the fix and passed five consecutive runs after the fix
  • Background startup tests and the full autocmd, startup, termcodes, terminal, messages, options, options_all, and help suites pass in a PTY with TEST_NO_RETRY=1, retaining platform and feature skips
  • Generated help-tag lookup and git diff --check pass

Local limitations are not counted as passes

  • The final terminal3 run still fails Test_term_keycode_translation, with the same failure reproduced three times after rebuilding the unchanged PR head source
  • A modeless-selection failure passed on targeted and full reruns
  • The existing experimental no-termresponse build configuration still has its previously recorded term_set_winsize link failure

GitHub verification for 61f336c is now complete

Comment thread src/term.c Resolved

@jparise jparise left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for working on this! I gave it a try and found a few issues (regressions) related to child commands to consider:

  • With the default termbackgroundwait=0, automatic background, and -c 'qall!', an OSC 11 reply sent 20ms after the query ends up being echoed after Vim exits.
  • With termbackgroundwait=50 and a startup :! command running a raw-terminal reader, Ctrl-C at 70ms followed by the background reply at 110ms lets the child read the literal OSC 11 response as input. The child receives no response bytes on the base revision.
  • With termbackgroundwait=50, set t_ti= t_te=, and a startup :! command, a dark reply at 80ms triggers a redraw after the final color reset. The child inherits Vim’s gray-on-black colors.

akasakariko added a commit to akasakariko/vim that referenced this pull request Nov 5, 2026
Problem:  The startup background handoff test can send CTRL-C before
          startup commands run on a slow machine.
Solution: Start the input timers after an explicit handoff marker and
          exercise slow initialization in the existing test (akasakariko).

related: vim#21664

Assisted-by: Codex
Signed-off-by: akasakariko <[email protected]>
@akasakariko
akasakariko force-pushed the fix/startup-background-21605 branch from 99be34e to 6056bb5 Compare November 5, 2026 14:45
@akasakariko
akasakariko force-pushed the fix/startup-background-21605 branch 3 times, most recently from 6aabc6b to 9cca569 Compare November 5, 2026 15:29
akasakariko added a commit to akasakariko/vim that referenced this pull request Nov 5, 2026
Problem:  The Windows SGR regression test can select WinPTY, which
          drops underline attributes, or launch a GUI in DLL builds.
Solution: Use the console sibling executable with ConPTY, retaining
          the existing text, underline and exit assertions (akasakariko).

Report unavailable ConPTY as a feature skip on older Windows versions.

related: vim#21664
Signed-off-by: akasakariko <[email protected]>
akasakariko added a commit to akasakariko/vim that referenced this pull request Nov 5, 2026
Problem:  Slow Azure mirror downloads and inconsistent cached debug
          indexes can abort CI before Vim is compiled or tested.
Solution: Select the primary Ubuntu archive over HTTPS in source and
          mirror lists, bound waits for downloads, and retry full index
          refreshes after clearing stale debug metadata (akasakariko).

Return the final APT error if all retries fail.

related: vim#21664
Signed-off-by: akasakariko <[email protected]>
@akasakariko
akasakariko force-pushed the fix/startup-background-21605 branch from 92ee40e to c55cd7f Compare November 5, 2026 17:38
@chrisbra

chrisbra commented Nov 5, 2026

Copy link
Copy Markdown
Member

I can't find it, I just remember there was an email thread in vim.dev about vim unexpectedly changing colors after some time (due to late terminal response to t_RB or something).

This is the revert 27822a0

@akasakariko

Copy link
Copy Markdown
Contributor Author

Thanks @jparise, all three issues raised in your review have been addressed in 4ca831d

@h-east

h-east commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

With the default 'termbackgroundwait' (0), this PR sends the OSC 11
query before the -c commands. master does not send it for -c qa.

I used the script below (Python 3, tried on Linux). It runs
vim --clean -c qa on a pty and replies to OSC 11 after DELAY ms
(no reply with -1).

python3 osc11_term.py /path/to/vim DELAY

Vim takes 100 ms longer to quit, also when the reply comes after
1 ms:

DELAY   master   PR
1       30 ms    132 ms
20      31 ms    136 ms
-1      45 ms    131 ms

With DELAY 150 the reply comes after Vim quits. It is shown in the
shell and is read by the next program:

$ python3 osc11_term.py /path/to/vim 150
master:
  shown in the shell:
  unread input: b''
PR:
  shown in the shell: ^[]11;rgb:0000/0000/0000^[\
  unread input: b'\x1b]11;rgb:0000/0000/0000\x1b\\'
osc11_term.py
#!/usr/bin/env python3
# Fake terminal that answers the OSC 11 query after DELAY ms.
# Usage: python3 osc11_term.py VIM DELAY_MS   (DELAY_MS < 0: no reply)
# Runs "VIM --clean -c qa" on a pty, then shows how long Vim took and
# what the shell got after Vim exited.
import os, pty, select, struct, sys, termios, fcntl, time

vim, delay = sys.argv[1], int(sys.argv[2])
after = ("import os,sys,termios,time; time.sleep(0.5); fd=0; "
         "a=termios.tcgetattr(fd); b=termios.tcgetattr(fd); "
         "b[3]&=~(termios.ICANON|termios.ECHO); b[6][termios.VMIN]=0; "
         "b[6][termios.VTIME]=0; termios.tcsetattr(fd,termios.TCSANOW,b); "
         "d=os.read(fd,4096); termios.tcsetattr(fd,termios.TCSANOW,a); "
         "print('unread input:', repr(d))")
pid, fd = pty.fork()
if pid == 0:
    os.environ['TERM'] = 'xterm-256color'
    os.execvp('sh', ['sh', '-c', '"$0" --clean -c qa; printf "@EXIT@"; '
                     'python3 -c "$1"', vim, after])
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', 24, 80, 0, 0))

start = time.monotonic()
out, reply_at, replied, exited = b'', None, False, None
while time.monotonic() < start + 3:
    if select.select([fd], [], [], 0.005)[0]:
        try:
            data = os.read(fd, 4096)
        except OSError:
            break
        if not data:
            break
        out += data
    now = time.monotonic()
    if reply_at is None and delay >= 0 and b'\x1b]11;?' in out:
        reply_at = now + delay / 1000
    if reply_at and not replied and now >= reply_at:
        os.write(fd, b'\x1b]11;rgb:0000/0000/0000\x1b\\')
        replied = True
    if exited is None and b'@EXIT@' in out:
        exited = now

print('OSC 11 query sent:', b'\x1b]11;?' in out)
print('Vim took: %d ms' % ((exited - start) * 1000))
rest = out.split(b'@EXIT@', 1)[1]
shown, _, unread = rest.partition(b'unread input:')
print('shown in the shell:', shown.decode(errors='replace').strip())
print('unread input:', unread.decode(errors='replace').strip())

Also, about four commits only change the CI results, and I don't know
if they are right fixes: 8d75369, e42c079, 9e49194, c55cd7f

akasakariko added a commit to akasakariko/vim that referenced this pull request Nov 7, 2026
Problem:  An early OSC 11 query with termbackgroundwait=0 adds an exit
          delay and can leave a late response in the caller's input.
Solution: Query before startup commands only when the wait is positive,
          document the default query timing, and cover both default and
          opt-in exits (akasakariko).

Restore the unrelated CI configuration and terminal tests to the base
revision, retaining the startup background test's true-color setup.

related: vim#21664
Signed-off-by: akasakariko <[email protected]>
@akasakariko

Copy link
Copy Markdown
Contributor Author

Thanks @h-east, fixed in 497f025

With the default termbackgroundwait=0, the background query is now deferred until after startup commands, so vim --clean -c qa sends no OSC 11 query
The early query is only enabled for a positive wait value

I reproduced the exit delay and late-response leak with your script before the fix
After the fix, DELAY values of 1, 20, -1, and 150 ms all produced no query, no shell echo, and empty unread input, with local exit times of 19–21 ms
The existing tests now cover default and explicit zero query deferral, alongside positive-wait exit and child-command handoff

I also removed the unrelated CI, APT, Filelist, and terminal3 changes from the PR diff
The startup background test retains its true-color setup so its first-background assertion is independent of the parent terminal palette

Local build and the startup, termcodes, options, messages, and autocmd suites passed with platform and feature skips
The startup suite uses the system Bash because the Homebrew Bash run failed in the existing stdin test's shell-exit cleanup
CI is running on the new commit and I am following its results

@akasakariko

Copy link
Copy Markdown
Contributor Author

CI follow-up for 497f025

All checks have finished, with 33 reported as successful and 7 failed

Five test jobs fail in Test_crash1_2 at the same crash 6 / Xdiff step: Linux HUGE GCC, Linux HUGE Clang, Linux ASan newtests 2, and both macOS HUGE builds
The upstream 88d96a15f run already has the same failure
This is the slowdown reported in #21678, with a proposed fix in the still-open #21782
The PR checks test merge ffe2493 against that newer upstream revision

I built upstream 88d96a1 locally and measured about 4.4 seconds for the failing test, compared with about 0.5 seconds on this branch
In a separate local worktree, this PR combined with upstream and the #21782 patch passes the complete crash, startup, and termcodes suites
The #21782 changes have not been added to this PR

Both Codecov checks remain red with incomplete uploads, including skipped uploads from the failed HUGE jobs
The GTK4 job is reported as successful because the existing workflow allows its test failure, but its test step timed out after 20 minutes while running Test_cscopeWithCscopeConnections and its coverage upload was skipped

The upstream rerun API returns HTTP 403 for this account
The outstanding prerequisite is the upstream diff performance fix, followed by a fresh CI run and coverage verification

akasakariko added a commit to akasakariko/vim that referenced this pull request Nov 7, 2026
Problem:  Current upstream makes Test_crash1_2 time out in several CI
          configurations, preventing complete coverage uploads.
Solution: Integrate the diff fold performance fix from PR vim#21782,
          preserving its original commit and author (akasakariko).

related: vim#21664
related: vim#21782
Signed-off-by: akasakariko <[email protected]>
@akasakariko

Copy link
Copy Markdown
Contributor Author

Follow-up in b1a91cd

Integrated the original #21782 commit 8f37741 to address the upstream diff fold slowdown that caused five Test_crash1_2 failures
The dependency and original authorship are preserved in the merge history and documented in the PR body

The complete diffmode, fold, crash, startup, termcodes, options, messages, and autocmd suites pass locally, with 616 tests executed and the existing platform and feature skips
Test_crash1_2 completes in about 940 ms
Two initial local diff runs hit timeouts while the external volume was slow, and all eight suites passed using the same binary with test scratch files on the system temporary volume

A fresh full CI run is starting on this head, including the coverage uploads missing from the previous failed jobs
The previous CI configuration, thresholds, and assertions remain intact

@akasakariko

Copy link
Copy Markdown
Contributor Author

CI result for b1a91cd: all 40 GitHub checks report success, with no pending checks

The five previous Test_crash1_2 failures are resolved, and both coverage checks pass after the full terminal and GUI coverage uploads
Patch coverage is 89.79% and project coverage is 83.14%, compared against upstream 88d96a1

Completed CI run

One qualification from the job logs: GTK4 still timed out in Test_cscopeWithCscopeConnections under the repository's existing continue-on-error policy
Its green job status is not evidence that the complete GTK4 suite passed
No workflow policy, timeout, assertion, or coverage threshold was changed in this follow-up

@jparise jparise left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In my local experiment, I also had this idea for both color response redraws:

if (starting == 0)
    redraw_asap(UPD_CLEAR);
else
    redraw_later(UPD_CLEAR);

The thinking is that we only need to update the colors but don't need to (re)draw until startup has finished preparing the buffer. I'm not sure this improves the output presentation in practice though.

akasakariko added a commit to akasakariko/vim that referenced this pull request Nov 12, 2026
Problem:  Color responses request an immediate redraw while startup is
          still preparing buffers.
Solution: Defer both the automatic background response redraw and the
          OSC autocmd redraw until startup has finished, retaining
          immediate redraws afterwards (Asuka).

related: vim#21664
Signed-off-by: Asuka <[email protected]>
akasakariko added a commit to akasakariko/vim that referenced this pull request Nov 12, 2026
Problem:  This branch's comparison still includes the diff fold performance
          fix now integrated in upstream master.
Solution: Merge current master to remove the redundant dependency from
          the PR diff while retaining its original history (Asuka).

related: vim#21664
related: vim#21782
Signed-off-by: Asuka <[email protected]>
@akasakariko

akasakariko commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @jparise, applied to both redraw call sites in 9f3389a

The background value is still updated immediately, with redraw_later(UPD_CLEAR) during startup and redraw_asap(UPD_CLEAR) afterwards

I compared PTY captures for both automatic background detection and an OSC autocmd changing background
Startup output was identical byte for byte in those cases, consistent with RedrawingDisabled already suppressing painting
Both paths still repaint after startup without keyboard input

The Huge and Tiny builds and the complete startup, termcodes, messages, autocmd, options, and terminal suites pass locally with the existing skips
CI is pending on 41bfb87

I also merged current master, so the fix from #21782 is now supplied by upstream and its diff no longer appears in this PR

@chrisbra chrisbra 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.

Can you please squash into a single commit? There are a few commits that are unrelated to the PR, so I'd like to see the final version. Also I noticed the below:

Comment thread src/main.c
// Do not read redirected input before executing startup commands.
if (stdout_isatty && mch_input_isatty())
may_req_bg_color();
# endif

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.

The comment is wrong, the code does not check 'termbackgroundwait'. Also, I think you need to exclude that the gui is running, similar to what is happening in the if branch above.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 3a39bd1

The call site now explicitly checks p_tbw > 0, terminal input and output, and !gui.in_use && !gui.starting
The existing default, zero-wait, positive-wait, and redirected-input startup tests pass

Comment thread src/os_unix.c
// Handle pending terminal responses before restoring cooked mode,
// otherwise they may be echoed as typed text.
stoptermcap();
settmode(TMODE_COOK);

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.

switching to cooked mode a bit later here, isn't this causing issues with exit_scroll(), because that one expects that the terminal is already in cooked mode?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I checked this with PTY captures and could not reproduce a missing carriage return
The screen-output path calls out_char('\n'), which emits CR-LF even in raw mode
Alternate-screen, non-swapping t_ti, empty t_ti, Ex mode, help, and version output all preserve CR-LF locally

In 3a39bd1, the existing handoff test now prints an exit message with a nonempty, non-swapping t_ti and asserts CR-LF before the t_te marker, while retaining its late-response leakage check
I also added an explanatory comment at the call site

Temporarily moving settmode(TMODE_COOK) back before exit_scroll() makes the handoff test fail by echoing the late OSC 11 response
I therefore kept the raw-mode handoff ordering rather than restoring the earlier cooked-mode transition

akasakariko added a commit to akasakariko/vim that referenced this pull request Nov 14, 2026
Problem:  Vim may draw a light background in a dark terminal before receiving
          the terminal background color response.
Solution: Add the opt-in 'termbackgroundwait' option to query and wait before
          the first screen clear, while keeping startup non-blocking by
          default (akasakariko).

Measure the wait using elapsed time where supported and stop for a response,
pending input or an interrupt. Only query early with a positive wait value,
terminal input and output, and no GUI. Defer redraws until startup finishes.

Consume OSC notifications without losing typed input or suppressing SafeState.
Keep raw mode until pending responses have been handled during terminal
handoff, and restore terminal colors before running child commands. Verify
that exit_scroll() still emits CR-LF before stoptermcap() in raw mode.

Document the option, its default of zero and the late-response limitation,
and cover startup colors, waiting, input preservation and terminal handoff.

fixes:   vim#21605
closes:  vim#21664
Signed-off-by: akasakariko <[email protected]>
@akasakariko
akasakariko force-pushed the fix/startup-background-21605 branch from 41bfb87 to 3a39bd1 Compare November 14, 2026 02:50
@akasakariko

Copy link
Copy Markdown
Contributor Author

Squashed the PR into one commit, 3a39bd1, as requested
The final diff contains no CI configuration or unrelated diff performance changes

  • Added the explicit positive-wait and GUI guards at the startup query call site
  • Verified the exit_scroll() concern and extended the existing handoff test to assert CR-LF before terminal teardown
  • Kept response handling before the cooked-mode transition because restoring the earlier ordering reproduces the late OSC 11 echo

Local Huge and Tiny builds, Tiny-compatible tests, eight relevant suites, codestyle, preprocessor indentation, and whitespace checks pass
The final suite runs report 1023 passed tests and 16 existing skips with TEST_NO_RETRY=1
The PR body records the initial Ctrl-C and WinScrolled failures, baseline comparison, and successful targeted and complete reruns

CI for the new commit is pending

Problem:  Vim may draw a light background in a dark terminal before receiving
          the terminal background color response.
Solution: Add the opt-in 'termbackgroundwait' option to query and wait before
          the first screen clear, while keeping startup non-blocking by
          default (akasakariko).

Measure the wait using elapsed time where supported and stop for a response,
pending input or an interrupt. Only query early with a positive wait value,
terminal input and output, and no GUI. Defer redraws until startup finishes.

Consume OSC notifications without losing typed input or suppressing SafeState.
Keep raw mode until pending responses have been handled during terminal
handoff, and restore terminal colors before running child commands. Verify
that exit_scroll() still emits CR-LF before stoptermcap() in raw mode.

Document the option, its default of zero and the late-response limitation,
and cover startup colors, waiting, input preservation and terminal handoff.

fixes:   vim#21605
closes:  vim#21664
Signed-off-by: akasakariko <[email protected]>
@akasakariko
akasakariko force-pushed the fix/startup-background-21605 branch from 3a39bd1 to 48cf56f Compare November 14, 2026 08:27
@chrisbra chrisbra closed this in d802230 Nov 21, 2026
@chrisbra

Copy link
Copy Markdown
Member

thanks

@h-east

h-east commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Since 9.2.1375, when 'termbackgroundwait' is set to a positive value,
the background color request is sent before the "-c" commands are
executed. When the terminal answers after the wait has ended, the
response is echoed as typed text:

  • With "vim -c q" the response appears in the shell Vim was started
    from.
  • With "vim -c '!cmd'" the response appears while the shell command
    is running.

Before 9.2.1375 the request was sent after the "-c" commands, as the
comment above may_req_termresponse() in main.c describes:

// Requesting the termresponse is postponed until here, so that a
// "-c q" argument doesn't make it appear in the shell Vim was
// started from.

A response that takes longer than 'termbackgroundwait' plus 100 msec
can happen over ssh or a terminal multiplexer.

Steps to reproduce

A real terminal answers too quickly, so this script runs a command in
a pty and answers the OSC 11 request after 400 msec:

import os, pty, re, select, sys, time

pid, fd = pty.fork()
if pid == 0:
    os.environ['TERM'] = 'xterm'
    os.execvp('sh', ['sh', '-c', sys.argv[1]])
out, answer_at, start = b'', None, time.monotonic()
while time.monotonic() - start < 5:
    if answer_at and time.monotonic() >= answer_at:
        os.write(fd, b'\x1b]11;rgb:0000/0000/0000\x1b\\')
        answer_at = 0
    if select.select([fd], [], [], 0.01)[0]:
        try:
            data = os.read(fd, 4096)
        except OSError:
            break
        if not data:
            break
        out += data
        if answer_at is None and re.search(rb'\x1b\]11;\?', out):
            answer_at = time.monotonic() + 0.4
print('echoed' if b'^[]11;rgb' in out else 'not echoed')

Save it as repro.py and run:

python3 repro.py "vim -u NONE -N --cmd 'set tbw=50' -c q; sleep 1"
python3 repro.py "vim -u NONE -N --cmd 'set tbw=50' -c '!sleep 1'"

Result

9.2.1375 prints "echoed" for both commands. The terminal output
contains:

^[]11;rgb:0000/0000/0000^[\

9.2.1374 (with "silent! set tbw=50") prints "not echoed" for both.

akasakariko added a commit to akasakariko/akasakariko that referenced this pull request Nov 22, 2026
@akasakariko

Copy link
Copy Markdown
Contributor Author

Thanks @h-east. I reproduced both cases on Vim 9.2.1382 with your script, tbw=50, and the 400 ms response delay. Both commands printed echoed before the fix.

I've opened #21985 to defer the background query when +, -c, or -S startup commands are present. If Vim continues after the commands, the existing query still detects the background. Ordinary interactive startup retains the early query and wait; the command-line restriction is documented.

With the fix, both of your commands print not echoed. The new PTY regression covers immediate exit, a shell command, +q, -S, and an indirect execute 'q'; all five cases reproduce the leak on the unmodified binary and pass with the fix. The local Huge build succeeds without warnings, and the startup, terminal-code, options, help, and code-style suites report 256 passing tests and 12 platform or feature skips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI assisted CI GHA, Cirrus, AppVeyor, ... platform-windows

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants