Skip to content

Console.Clear() doesn't clear the scrollback buffer on Unix-like platforms #28355

Closed

Description

@mklement0

Console.Clear()'s documentation states (emphasis added):

Clears the console buffer and corresponding console window of display information.

Indeed, not just clearing the current terminal window (screen), but also the scrollback buffer is the typical use case, and it is how this method has always worked on Windows.[1]

By contrast, the Unix implementation currently only clears the screen, which makes for an inconsistent cross-platform experience.

While there is no POSIX-compliant way to clear the scrollback buffer (only clearing the screen is mandated by POSIX, via tput clear), xterm-compatible terminal applications do support escape sequence <esc>[3J - see Wikipedia.

In practice, the macOS terminal application and the one on Ubuntu, for instance, do support this escape sequence - generally, terminal emulators based on the X Window System.

I don't know if there are popular terminal emulators out there that do not support it, but even a best-effort implementation would be useful.

Here's a workaround that demonstrates use of the escape sequence:

// Clears the screen and the scrollback buffer in xterm-compatible terminals.
Console.Clear(); Console.WriteLine("\x1b[3J")

[1] Whether there should be an opt-in for predictably clearing only the screen across platforms, while leaving the scrollback buffer intact, is a separate question.

Activity

  1. SteveL-MSFT commented on Jan 9, 2019

    @SteveL-MSFT
    Contributor

    Perhaps adding an overload with a bool includeScrollBackBuffer would retain current behavior and allow for the desired behavior

  2. mklement0 commented on Jan 9, 2019

    @mklement0
    Author

    @SteveL-MSFT: Given that (a) clearing the buffer is documented and (b) doing so is generally the more sensible behavior, my vote is to simply change the existing behavior to align with the documentation / the behavior on Windows.

  3. danmoseley commented on Jan 9, 2019

    @danmoseley
    Contributor

    @stephentoub do you recall whether this was intentional, to not attempt to clear scrollback if supported?

  4. stephentoub commented on Jan 9, 2019

    @stephentoub
    Member

    do you recall whether this was intentional, to not attempt to clear scrollback if supported?

    Not clearing it was not a goal. If there's a "safe" way to do it whenever it's possible (by safe I mean not emitting garbage to stdout when the particular escape code isn't supported by the terminal in use), such as relying on some reliable way to query that a compatible terminal is being used, I'm fine with doing so.

  5. mklement0 commented on Jan 9, 2019

    @mklement0
    Author

    Thanks, @stephentoub.

    relying on some reliable way to query that a compatible terminal is being used

    Based on the answers posted at https://unix.stackexchange.com/q/93376/54804, this should be as simple as:

    # ... perform screen clearing (as before)
    # In compatible terminals, also clear the scrollback buffer.
    if (Environment.GetEnvironmentVariable("TERM").StartsWith("xterm")) Console.WriteLine("\x1b[3J");

    xterm-compatible terminal emulators set env. var. TERM either to xterm or xterm-<colorCountSpec>, e.g., xterm-256color.

  6. stephentoub commented on Jan 9, 2019

    @stephentoub
    Member

    And presumably if we did that first and then did the current clear (rather than the opposite order), if we did end up for some reason generating garbage, it'd be mitigated by being immediately cleared? :)

  7. mklement0 commented on Jan 10, 2019

    @mklement0
    Author

    Exemplary garbage disposal, @stephentoub :)

  8. danmoseley commented on Jan 10, 2019

    @danmoseley
    Contributor

    @mklement0 do you wish to offer a PR?

  9. khellang commented on Jan 10, 2019

    @khellang
    Member

    You should be able to query the terminfo db for the E3 extension, no?

    See user_caps(5) under "Recognized capabilities":

    E3 string, tells how to clear the terminal's scrollback buffer.

    When present, the clear(1) program sends this before clearing the terminal.

    The command "tput clear" does the same thing.

  10. mklement0 commented on Jan 10, 2019

    @mklement0
    Author

    Thanks, @khellang, but in practice neither clear nor tput clear clear the scrollback buffer on macOS 10.14 and Ubuntu 18.04.

    Consistent with that, the requisite escape sequence, \E[3J, is not present in the output from infocmp when invoked from an xterm-compatible terminal.

    I know little about terminal-info databases, so maybe I'm missing something.

    @danmosemsft: I'll give it a shot.

  11. danmoseley commented on Jan 10, 2019

    @danmoseley
    Contributor

    @mklement0 sounds good. I sent you a collaborator invite: it's optional, if you accept it I can formally assign you. Note that accepting it switches on notifications for all of the repo, which you'll likely want to switch off again.

  12. mklement0 commented on Jan 11, 2019

    @mklement0
    Author

    Thanks, @danmosemsft; I've accepted the invitation.

  13. danmoseley commented on Jan 11, 2019

    @danmoseley
    Contributor

    Assigned.

  14. 23 remaining items

  15. added this to the 8.0.0 milestone on Nov 13, 2023
  16. iSazonov commented on Nov 14, 2023

    @iSazonov
    Contributor

    @adamsitnik It did not fix MacOS.

    1. Is it possible to add the MacOS fix using direct escapes?
    2. Or should we document the MacOS behavior exclusion for Console.Clear?
    3. Should we reopen the issue or Console.Clear() does not clear buffers on macOS core#8260?
  17. kasperk81 commented on Nov 14, 2023

    @kasperk81
    Contributor

    It did not fix MacOS.

    are you sure? i tried 8.0-rtm with

    Console.Clear();
    Console.WriteLine("Hello, World!");
    

    it clears the scrollback buffer on mac terminal and prints out Hello, World!
    7.0 doesn't clear the scrollback buffer

  18. hamarb123 commented on Nov 14, 2023

    @hamarb123
    Contributor

    Did you try printing a bunch of lines first, instead of immediately clearing @kasperk81 ?
    I've not tested it with the fix yet, but plan to tomorrow when 8.0 releases (but I'm not convinced it will work for macOS until I test it myself).

  19. kasperk81 commented on Nov 14, 2023

    @kasperk81
    Contributor

    of course i tested with overflown buffers and that's the difference between .net 8 vs 7

  20. hamarb123 commented on Nov 14, 2023

    @hamarb123
    Contributor

    of course

    How is it "of course" if it's not in the code you showed.

    Edit: I don't know why you're downvoting all my comments for trying to determine if this bug is fixed or not. It wasn't "of course" because your code didn't show it, I never said anything else had an issue, other than my personal doubt that it's fixed (because it's been a bug for years), I simply asked if you checked it since it wasn't in the code (therefore I assumed you hadn't checked it - why do you think I asked). I then pointed out it wasn't "of course", since it wasn't as I just explained.

  21. mklement0 commented on Nov 14, 2023

    @mklement0
    Author

    I just installed the officially released 8.0.100 version and I can confirm @iSazonov's findings: As far as I can tell, it does NOT work on macOS - neither in Terminal.app nor in popular third-party alternative iTerm2.app:

    Repro code (reproduces the symptom on macOS 13.5.2):

    for (var i = 0; i < 500; ++i) { Console.WriteLine(i); }; 
    Console.Write("Press a key to clear the terminal"); 
    Console.ReadKey(true); 
    Console.Clear();  // Scroll back up afterwards - you'll see that the numbers are still there.

    By contrast, adding the escape sequence that clears the scrollback buffer shown in the initial post works, in both terminal applications:

    Console.Clear(); Console.WriteLine("\x1b[3J");

    Shell alternatives:

    Note: /usr/bin/clear on macOS clears only the current screen, not the scrollback buffer.

    • Bash
    /usr/bin/clear; printf '\x1b[3J'
    • PowerShell
    /usr/bin/clear; printf "`e[3J"
  22. kasperk81 commented on Nov 14, 2023

    @kasperk81
    Contributor

    Repro code (reproduces the symptom on macOS 13.5.2):

    i'm on 14 (sonoma) and i don't see the numbers afterwards

  23. hamarb123 commented on Nov 14, 2023

    @hamarb123
    Contributor

    Can confirm the following for Terminal.app:

    • Fixed on macOS 14.1
    • Broken on macOS 13.6.1

    We should fix this since macOS 10.15+ is supported for .NET 8.

  24. adamsitnik commented on Nov 15, 2023

    @adamsitnik
    Member

    The referenced fix (#88487) checks the terminfo for an E3 capability and uses it (not a hardcoded "\x1b[3J") when it's available.

    I would love to fix it for all terminals, but how can we do that reliably if they don't define this capability? Sharing https://unix.stackexchange.com/questions/375743/why-clear-do-not-clear-whole-screen/375784#375784 for reference.

  25. mklement0 commented on Nov 15, 2023

    @mklement0
    Author

    @adamsitnik: Given @hamarb123's summary above, there's a pragmatic solution:

    Instead of:

    if (db.GetExtendedString("E3") is string clearScrollbackBuffer)
    {
    Clear += clearScrollbackBuffer; // the E3 command must come after the Clear command
    }

    use:

    if (
      (
        RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && Environment.OSVersion.Version.Major < 14 ?
          "\x1b[3J"
          :
          db.GetExtendedString("E3")
      ) is string clearScrollbackBuffer
    )
    {
        Clear += clearScrollbackBuffer; // the E3 command must come after the Clear command
    }

    Windows is not affected, and I'm not aware of issues on Linux distros, so this should be the only workaround required.

    Once .NET no longer supports macOS 13 and below, this workaround can be removed.

  26. hamarb123 commented on Nov 15, 2023

    @hamarb123
    Contributor

    I think something like the above is a good solution. (OperatingSystem.IsMacOS() && !OperatingSystem.IsMacOSVersionAtLeast(14) seems better suited though)

    Note that with dotnet/roslyn#70497, we should be able to even write \e[3J with C# next :)

    If it concerns you that it might print something random out after it @adamsitnik, you could also re-append TermInfo.WellKnownStrings.Clear (or something similar) to it again to ensure that a clear goes through for this workaround - it seems to me like this should work well in most cases.

    Ie, you could write:

    if (db.GetExtendedString("E3") is string clearScrollbackBuffer)
    {
        Clear += clearScrollbackBuffer; // the E3 command must come after the Clear command
    }
    else if (OperatingSystem.IsMacOS() && !OperatingSystem.IsMacOSVersionAtLeast(14))
    {
        Clear += "\e[3J" + db.GetString(TermInfo.WellKnownStrings.Clear); //use \e[3J to do a full clear on macOS terminal, and print the clear string again in case some terminal emulators don't understand this code to ensure we don't get random characters printed out
    }

    (note: I've not tested the above actually does what it's intended to)

    I can make a PR for it if you'd like @adamsitnik

  27. adamsitnik commented on Nov 16, 2023

    @adamsitnik
    Member

    The solution that you suggested assumes that every Terminal that runs on macOS supports "\x1b[3J". I doubt it's always true.

    Don't get me wrong, I want to get all the bugs fixed. But in reliable way.

    My current best idea is to recognize the Terminals that support it, but don't define that in Terminfo. Similarly to what we do in:

    IsRxvtTerm = !string.IsNullOrEmpty(db.Term) && db.Term.Contains("rxvt", StringComparison.OrdinalIgnoreCase);

    But I doubt that such a fix would be approved for backporting to .NET 8 (unless we can guarantee that older versions of this Terminals support it).

  28. hamarb123 commented on Nov 16, 2023

    @hamarb123
    Contributor

    The solution that you suggested assumes that every Terminal that runs on macOS supports "\x1b[3J". I doubt it's always true.

    The point of the way I suggested doing it is assuming that they don't all support it. That's why I suggested a normal clear after. Would that not work?

  29. locked and limited conversation to collaborators on Dec 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions