/ ink / clearTerminal.ts
clearTerminal.ts
 1  /**
 2   * Cross-platform terminal clearing with scrollback support.
 3   * Detects modern terminals that support ESC[3J for clearing scrollback.
 4   */
 5  
 6  import {
 7    CURSOR_HOME,
 8    csi,
 9    ERASE_SCREEN,
10    ERASE_SCROLLBACK,
11  } from './termio/csi.js'
12  
13  // HVP (Horizontal Vertical Position) - legacy Windows cursor home
14  const CURSOR_HOME_WINDOWS = csi(0, 'f')
15  
16  function isWindowsTerminal(): boolean {
17    return process.platform === 'win32' && !!process.env.WT_SESSION
18  }
19  
20  function isMintty(): boolean {
21    // mintty 3.1.5+ sets TERM_PROGRAM to 'mintty'
22    if (process.env.TERM_PROGRAM === 'mintty') {
23      return true
24    }
25    // GitBash/MSYS2/MINGW use mintty and set MSYSTEM
26    if (process.platform === 'win32' && process.env.MSYSTEM) {
27      return true
28    }
29    return false
30  }
31  
32  function isModernWindowsTerminal(): boolean {
33    // Windows Terminal sets WT_SESSION environment variable
34    if (isWindowsTerminal()) {
35      return true
36    }
37  
38    // VS Code integrated terminal on Windows with ConPTY support
39    if (
40      process.platform === 'win32' &&
41      process.env.TERM_PROGRAM === 'vscode' &&
42      process.env.TERM_PROGRAM_VERSION
43    ) {
44      return true
45    }
46  
47    // mintty (GitBash/MSYS2/Cygwin) supports modern escape sequences
48    if (isMintty()) {
49      return true
50    }
51  
52    return false
53  }
54  
55  /**
56   * Returns the ANSI escape sequence to clear the terminal including scrollback.
57   * Automatically detects terminal capabilities.
58   */
59  export function getClearTerminalSequence(): string {
60    if (process.platform === 'win32') {
61      if (isModernWindowsTerminal()) {
62        return ERASE_SCREEN + ERASE_SCROLLBACK + CURSOR_HOME
63      } else {
64        // Legacy Windows console - can't clear scrollback
65        return ERASE_SCREEN + CURSOR_HOME_WINDOWS
66      }
67    }
68    return ERASE_SCREEN + ERASE_SCROLLBACK + CURSOR_HOME
69  }
70  
71  /**
72   * Clears the terminal screen. On supported terminals, also clears scrollback.
73   */
74  export const clearTerminal = getClearTerminalSequence()