terminal.nim 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains a few procedures to control the *terminal*
  10. ## (also called *console*). On UNIX, the implementation simply uses ANSI escape
  11. ## sequences and does not depend on any other module, on Windows it uses the
  12. ## Windows API.
  13. ## Changing the style is permanent even after program termination! Use the
  14. ## code `exitprocs.addExitProc(resetAttributes)` to restore the defaults.
  15. ## Similarly, if you hide the cursor, make sure to unhide it with
  16. ## `showCursor` before quitting.
  17. ##
  18. ## Progress bar
  19. ## ============
  20. ##
  21. ## Basic progress bar example:
  22. runnableExamples("-r:off"):
  23. import std/[os, strutils]
  24. for i in 0..100:
  25. stdout.styledWriteLine(fgRed, "0% ", fgWhite, '#'.repeat i, if i > 50: fgGreen else: fgYellow, "\t", $i , "%")
  26. sleep 42
  27. cursorUp 1
  28. eraseLine()
  29. stdout.resetAttributes()
  30. ##[
  31. ## Playing with colorful and styled text
  32. ]##
  33. ## Procs like `styledWriteLine`, `styledEcho` etc. have a temporary effect on
  34. ## text parameters. Style parameters only affect the text parameter right after them.
  35. ## After being called, these procs will reset the default style of the terminal.
  36. ## While `setBackGroundColor`, `setForeGroundColor` etc. have a lasting
  37. ## influence on the terminal, you can use `resetAttributes` to
  38. ## reset the default style of the terminal.
  39. runnableExamples("-r:off"):
  40. stdout.styledWriteLine({styleBright, styleBlink, styleUnderscore}, "styled text ")
  41. stdout.styledWriteLine(fgRed, "red text ")
  42. stdout.styledWriteLine(fgWhite, bgRed, "white text in red background")
  43. stdout.styledWriteLine(" ordinary text without style ")
  44. stdout.setBackGroundColor(bgCyan, true)
  45. stdout.setForeGroundColor(fgBlue)
  46. stdout.write("blue text in cyan background")
  47. stdout.resetAttributes()
  48. # You can specify multiple text parameters. Style parameters
  49. # only affect the text parameter right after them.
  50. styledEcho styleBright, fgGreen, "[PASS]", resetStyle, fgGreen, " Yay!"
  51. stdout.styledWriteLine(fgRed, "red text ", styleBright, "bold red", fgDefault, " bold text")
  52. import macros
  53. import strformat
  54. from strutils import toLowerAscii, `%`
  55. import colors
  56. when defined(windows):
  57. import winlean
  58. when defined(nimPreviewSlimSystem):
  59. import std/[syncio, assertions]
  60. type
  61. PTerminal = ref object
  62. trueColorIsSupported: bool
  63. trueColorIsEnabled: bool
  64. fgSetColor: bool
  65. when defined(windows):
  66. hStdout: Handle
  67. hStderr: Handle
  68. oldStdoutAttr: int16
  69. oldStderrAttr: int16
  70. var gTerm {.threadvar.}: owned(PTerminal)
  71. when defined(windows) and defined(consoleapp):
  72. proc newTerminal(): owned(PTerminal) {.gcsafe, raises: [OSError].}
  73. else:
  74. proc newTerminal(): owned(PTerminal) {.gcsafe, raises: [].}
  75. proc getTerminal(): PTerminal {.inline.} =
  76. if isNil(gTerm):
  77. gTerm = newTerminal()
  78. result = gTerm
  79. const
  80. fgPrefix = "\e[38;2;"
  81. bgPrefix = "\e[48;2;"
  82. ansiResetCode* = "\e[0m"
  83. stylePrefix = "\e["
  84. when defined(windows):
  85. import winlean, os
  86. const
  87. DUPLICATE_SAME_ACCESS = 2
  88. FOREGROUND_BLUE = 1
  89. FOREGROUND_GREEN = 2
  90. FOREGROUND_RED = 4
  91. FOREGROUND_INTENSITY = 8
  92. BACKGROUND_BLUE = 16
  93. BACKGROUND_GREEN = 32
  94. BACKGROUND_RED = 64
  95. BACKGROUND_INTENSITY = 128
  96. FOREGROUND_RGB = FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_BLUE
  97. BACKGROUND_RGB = BACKGROUND_RED or BACKGROUND_GREEN or BACKGROUND_BLUE
  98. ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
  99. type
  100. SHORT = int16
  101. COORD = object
  102. x: SHORT
  103. y: SHORT
  104. SMALL_RECT = object
  105. left: SHORT
  106. top: SHORT
  107. right: SHORT
  108. bottom: SHORT
  109. CONSOLE_SCREEN_BUFFER_INFO = object
  110. dwSize: COORD
  111. dwCursorPosition: COORD
  112. wAttributes: int16
  113. srWindow: SMALL_RECT
  114. dwMaximumWindowSize: COORD
  115. CONSOLE_CURSOR_INFO = object
  116. dwSize: DWORD
  117. bVisible: WINBOOL
  118. proc duplicateHandle(hSourceProcessHandle: Handle, hSourceHandle: Handle,
  119. hTargetProcessHandle: Handle, lpTargetHandle: ptr Handle,
  120. dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
  121. dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
  122. importc: "DuplicateHandle".}
  123. proc getCurrentProcess(): Handle{.stdcall, dynlib: "kernel32",
  124. importc: "GetCurrentProcess".}
  125. proc getConsoleScreenBufferInfo(hConsoleOutput: Handle,
  126. lpConsoleScreenBufferInfo: ptr CONSOLE_SCREEN_BUFFER_INFO): WINBOOL{.stdcall,
  127. dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".}
  128. proc getConsoleCursorInfo(hConsoleOutput: Handle,
  129. lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
  130. stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".}
  131. proc setConsoleCursorInfo(hConsoleOutput: Handle,
  132. lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
  133. stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".}
  134. proc terminalWidthIoctl*(handles: openArray[Handle]): int =
  135. var csbi: CONSOLE_SCREEN_BUFFER_INFO
  136. for h in handles:
  137. if getConsoleScreenBufferInfo(h, addr csbi) != 0:
  138. return int(csbi.srWindow.right - csbi.srWindow.left + 1)
  139. return 0
  140. proc terminalHeightIoctl*(handles: openArray[Handle]): int =
  141. var csbi: CONSOLE_SCREEN_BUFFER_INFO
  142. for h in handles:
  143. if getConsoleScreenBufferInfo(h, addr csbi) != 0:
  144. return int(csbi.srWindow.bottom - csbi.srWindow.top + 1)
  145. return 0
  146. proc terminalWidth*(): int =
  147. ## Returns the terminal width in columns.
  148. var w: int = 0
  149. w = terminalWidthIoctl([getStdHandle(STD_INPUT_HANDLE),
  150. getStdHandle(STD_OUTPUT_HANDLE),
  151. getStdHandle(STD_ERROR_HANDLE)])
  152. if w > 0: return w
  153. return 80
  154. proc terminalHeight*(): int =
  155. ## Returns the terminal height in rows.
  156. var h: int = 0
  157. h = terminalHeightIoctl([getStdHandle(STD_INPUT_HANDLE),
  158. getStdHandle(STD_OUTPUT_HANDLE),
  159. getStdHandle(STD_ERROR_HANDLE)])
  160. if h > 0: return h
  161. return 0
  162. proc setConsoleCursorPosition(hConsoleOutput: Handle,
  163. dwCursorPosition: COORD): WINBOOL{.
  164. stdcall, dynlib: "kernel32", importc: "SetConsoleCursorPosition".}
  165. proc fillConsoleOutputCharacter(hConsoleOutput: Handle, cCharacter: char,
  166. nLength: DWORD, dwWriteCoord: COORD,
  167. lpNumberOfCharsWritten: ptr DWORD): WINBOOL{.
  168. stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".}
  169. proc fillConsoleOutputAttribute(hConsoleOutput: Handle, wAttribute: int16,
  170. nLength: DWORD, dwWriteCoord: COORD,
  171. lpNumberOfAttrsWritten: ptr DWORD): WINBOOL{.
  172. stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".}
  173. proc setConsoleTextAttribute(hConsoleOutput: Handle,
  174. wAttributes: int16): WINBOOL{.
  175. stdcall, dynlib: "kernel32", importc: "SetConsoleTextAttribute".}
  176. proc getConsoleMode(hConsoleHandle: Handle, dwMode: ptr DWORD): WINBOOL{.
  177. stdcall, dynlib: "kernel32", importc: "GetConsoleMode".}
  178. proc setConsoleMode(hConsoleHandle: Handle, dwMode: DWORD): WINBOOL{.
  179. stdcall, dynlib: "kernel32", importc: "SetConsoleMode".}
  180. proc getCursorPos(h: Handle): tuple [x, y: int] =
  181. var c: CONSOLE_SCREEN_BUFFER_INFO
  182. if getConsoleScreenBufferInfo(h, addr(c)) == 0:
  183. raiseOSError(osLastError())
  184. return (int(c.dwCursorPosition.x), int(c.dwCursorPosition.y))
  185. proc setCursorPos(h: Handle, x, y: int) =
  186. var c: COORD
  187. c.x = int16(x)
  188. c.y = int16(y)
  189. if setConsoleCursorPosition(h, c) == 0:
  190. raiseOSError(osLastError())
  191. proc getAttributes(h: Handle): int16 =
  192. var c: CONSOLE_SCREEN_BUFFER_INFO
  193. # workaround Windows bugs: try several times
  194. if getConsoleScreenBufferInfo(h, addr(c)) != 0:
  195. return c.wAttributes
  196. return 0x70'i16 # ERROR: return white background, black text
  197. proc initTerminal(term: PTerminal) =
  198. var hStdoutTemp = getStdHandle(STD_OUTPUT_HANDLE)
  199. if duplicateHandle(getCurrentProcess(), hStdoutTemp, getCurrentProcess(),
  200. addr(term.hStdout), 0, 1, DUPLICATE_SAME_ACCESS) == 0:
  201. when defined(consoleapp):
  202. raiseOSError(osLastError())
  203. var hStderrTemp = getStdHandle(STD_ERROR_HANDLE)
  204. if duplicateHandle(getCurrentProcess(), hStderrTemp, getCurrentProcess(),
  205. addr(term.hStderr), 0, 1, DUPLICATE_SAME_ACCESS) == 0:
  206. when defined(consoleapp):
  207. raiseOSError(osLastError())
  208. term.oldStdoutAttr = getAttributes(term.hStdout)
  209. term.oldStderrAttr = getAttributes(term.hStderr)
  210. template conHandle(f: File): Handle =
  211. let term = getTerminal()
  212. if f == stderr: term.hStderr else: term.hStdout
  213. else:
  214. import termios, posix, os, parseutils
  215. proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) =
  216. var mode: Termios
  217. discard fd.tcGetAttr(addr mode)
  218. mode.c_iflag = mode.c_iflag and not Cflag(BRKINT or ICRNL or INPCK or
  219. ISTRIP or IXON)
  220. mode.c_oflag = mode.c_oflag and not Cflag(OPOST)
  221. mode.c_cflag = (mode.c_cflag and not Cflag(CSIZE or PARENB)) or CS8
  222. mode.c_lflag = mode.c_lflag and not Cflag(ECHO or ICANON or IEXTEN or ISIG)
  223. mode.c_cc[VMIN] = 1.cuchar
  224. mode.c_cc[VTIME] = 0.cuchar
  225. discard fd.tcSetAttr(time, addr mode)
  226. proc terminalWidthIoctl*(fds: openArray[int]): int =
  227. ## Returns terminal width from first fd that supports the ioctl.
  228. var win: IOctl_WinSize
  229. for fd in fds:
  230. if ioctl(cint(fd), TIOCGWINSZ, addr win) != -1:
  231. return int(win.ws_col)
  232. return 0
  233. proc terminalHeightIoctl*(fds: openArray[int]): int =
  234. ## Returns terminal height from first fd that supports the ioctl.
  235. var win: IOctl_WinSize
  236. for fd in fds:
  237. if ioctl(cint(fd), TIOCGWINSZ, addr win) != -1:
  238. return int(win.ws_row)
  239. return 0
  240. var L_ctermid{.importc, header: "<stdio.h>".}: cint
  241. proc terminalWidth*(): int =
  242. ## Returns some reasonable terminal width from either standard file
  243. ## descriptors, controlling terminal, environment variables or tradition.
  244. # POSIX environment variable takes precendence.
  245. # _COLUMNS_: This variable shall represent a decimal integer >0 used
  246. # to indicate the user's preferred width in column positions for
  247. # the terminal screen or window. If this variable is unset or null,
  248. # the implementation determines the number of columns, appropriate
  249. # for the terminal or window, in an unspecified manner.
  250. # When COLUMNS is set, any terminal-width information implied by TERM
  251. # is overridden. Users and conforming applications should not set COLUMNS
  252. # unless they wish to override the system selection and produce output
  253. # unrelated to the terminal characteristics.
  254. # See POSIX Base Definitions Section 8.1 Environment Variable Definition
  255. var w: int
  256. var s = getEnv("COLUMNS") # Try standard env var
  257. if len(s) > 0 and parseSaturatedNatural(s, w) > 0 and w > 0:
  258. return w
  259. w = terminalWidthIoctl([0, 1, 2]) # Try standard file descriptors
  260. if w > 0: return w
  261. var cterm = newString(L_ctermid) # Try controlling tty
  262. var fd = open(ctermid(cstring(cterm)), O_RDONLY)
  263. if fd != -1:
  264. w = terminalWidthIoctl([int(fd)])
  265. discard close(fd)
  266. if w > 0: return w
  267. return 80 # Finally default to venerable value
  268. proc terminalHeight*(): int =
  269. ## Returns some reasonable terminal height from either standard file
  270. ## descriptors, controlling terminal, environment variables or tradition.
  271. ## Zero is returned if the height could not be determined.
  272. # POSIX environment variable takes precendence.
  273. # _LINES_: This variable shall represent a decimal integer >0 used
  274. # to indicate the user's preferred number of lines on a page or
  275. # the vertical screen or window size in lines. A line in this case
  276. # is a vertical measure large enough to hold the tallest character
  277. # in the character set being displayed. If this variable is unset or null,
  278. # the implementation determines the number of lines, appropriate
  279. # for the terminal or window (size, terminal baud rate, and so on),
  280. # in an unspecified manner.
  281. # When LINES is set, any terminal-height information implied by TERM
  282. # is overridden. Users and conforming applications should not set LINES
  283. # unless they wish to override the system selection and produce output
  284. # unrelated to the terminal characteristics.
  285. # See POSIX Base Definitions Section 8.1 Environment Variable Definition
  286. var h: int
  287. var s = getEnv("LINES") # Try standard env var
  288. if len(s) > 0 and parseSaturatedNatural(s, h) > 0 and h > 0:
  289. return h
  290. h = terminalHeightIoctl([0, 1, 2]) # Try standard file descriptors
  291. if h > 0: return h
  292. var cterm = newString(L_ctermid) # Try controlling tty
  293. var fd = open(ctermid(cstring(cterm)), O_RDONLY)
  294. if fd != -1:
  295. h = terminalHeightIoctl([int(fd)])
  296. discard close(fd)
  297. if h > 0: return h
  298. return 0 # Could not determine height
  299. proc terminalSize*(): tuple[w, h: int] =
  300. ## Returns the terminal width and height as a tuple. Internally calls
  301. ## `terminalWidth` and `terminalHeight`, so the same assumptions apply.
  302. result = (terminalWidth(), terminalHeight())
  303. when defined(windows):
  304. proc setCursorVisibility(f: File, visible: bool) =
  305. var ccsi: CONSOLE_CURSOR_INFO
  306. let h = conHandle(f)
  307. if getConsoleCursorInfo(h, addr(ccsi)) == 0:
  308. raiseOSError(osLastError())
  309. ccsi.bVisible = if visible: 1 else: 0
  310. if setConsoleCursorInfo(h, addr(ccsi)) == 0:
  311. raiseOSError(osLastError())
  312. proc hideCursor*(f: File) =
  313. ## Hides the cursor.
  314. when defined(windows):
  315. setCursorVisibility(f, false)
  316. else:
  317. f.write("\e[?25l")
  318. proc showCursor*(f: File) =
  319. ## Shows the cursor.
  320. when defined(windows):
  321. setCursorVisibility(f, true)
  322. else:
  323. f.write("\e[?25h")
  324. proc setCursorPos*(f: File, x, y: int) =
  325. ## Sets the terminal's cursor to the (x,y) position.
  326. ## (0,0) is the upper left of the screen.
  327. when defined(windows):
  328. let h = conHandle(f)
  329. setCursorPos(h, x, y)
  330. else:
  331. f.write(fmt"{stylePrefix}{y+1};{x+1}f")
  332. proc setCursorXPos*(f: File, x: int) =
  333. ## Sets the terminal's cursor to the x position.
  334. ## The y position is not changed.
  335. when defined(windows):
  336. let h = conHandle(f)
  337. var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
  338. if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
  339. raiseOSError(osLastError())
  340. var origin = scrbuf.dwCursorPosition
  341. origin.x = int16(x)
  342. if setConsoleCursorPosition(h, origin) == 0:
  343. raiseOSError(osLastError())
  344. else:
  345. f.write(fmt"{stylePrefix}{x+1}G")
  346. when defined(windows):
  347. proc setCursorYPos*(f: File, y: int) =
  348. ## Sets the terminal's cursor to the y position.
  349. ## The x position is not changed.
  350. ## .. warning:: This is not supported on UNIX!
  351. when defined(windows):
  352. let h = conHandle(f)
  353. var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
  354. if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
  355. raiseOSError(osLastError())
  356. var origin = scrbuf.dwCursorPosition
  357. origin.y = int16(y)
  358. if setConsoleCursorPosition(h, origin) == 0:
  359. raiseOSError(osLastError())
  360. else:
  361. discard
  362. proc cursorUp*(f: File, count = 1) =
  363. ## Moves the cursor up by `count` rows.
  364. runnableExamples("-r:off"):
  365. stdout.cursorUp(2)
  366. write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
  367. when defined(windows):
  368. let h = conHandle(f)
  369. var p = getCursorPos(h)
  370. dec(p.y, count)
  371. setCursorPos(h, p.x, p.y)
  372. else:
  373. f.write("\e[" & $count & 'A')
  374. proc cursorDown*(f: File, count = 1) =
  375. ## Moves the cursor down by `count` rows.
  376. runnableExamples("-r:off"):
  377. stdout.cursorDown(2)
  378. write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
  379. when defined(windows):
  380. let h = conHandle(f)
  381. var p = getCursorPos(h)
  382. inc(p.y, count)
  383. setCursorPos(h, p.x, p.y)
  384. else:
  385. f.write(fmt"{stylePrefix}{count}B")
  386. proc cursorForward*(f: File, count = 1) =
  387. ## Moves the cursor forward by `count` columns.
  388. runnableExamples("-r:off"):
  389. stdout.cursorForward(2)
  390. write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
  391. when defined(windows):
  392. let h = conHandle(f)
  393. var p = getCursorPos(h)
  394. inc(p.x, count)
  395. setCursorPos(h, p.x, p.y)
  396. else:
  397. f.write(fmt"{stylePrefix}{count}C")
  398. proc cursorBackward*(f: File, count = 1) =
  399. ## Moves the cursor backward by `count` columns.
  400. runnableExamples("-r:off"):
  401. stdout.cursorBackward(2)
  402. write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
  403. when defined(windows):
  404. let h = conHandle(f)
  405. var p = getCursorPos(h)
  406. dec(p.x, count)
  407. setCursorPos(h, p.x, p.y)
  408. else:
  409. f.write(fmt"{stylePrefix}{count}D")
  410. when true:
  411. discard
  412. else:
  413. proc eraseLineEnd*(f: File) =
  414. ## Erases from the current cursor position to the end of the current line.
  415. when defined(windows):
  416. discard
  417. else:
  418. f.write("\e[K")
  419. proc eraseLineStart*(f: File) =
  420. ## Erases from the current cursor position to the start of the current line.
  421. when defined(windows):
  422. discard
  423. else:
  424. f.write("\e[1K")
  425. proc eraseDown*(f: File) =
  426. ## Erases the screen from the current line down to the bottom of the screen.
  427. when defined(windows):
  428. discard
  429. else:
  430. f.write("\e[J")
  431. proc eraseUp*(f: File) =
  432. ## Erases the screen from the current line up to the top of the screen.
  433. when defined(windows):
  434. discard
  435. else:
  436. f.write("\e[1J")
  437. proc eraseLine*(f: File) =
  438. ## Erases the entire current line.
  439. runnableExamples("-r:off"):
  440. write(stdout, "never mind")
  441. stdout.eraseLine() # nothing will be printed on the screen
  442. when defined(windows):
  443. let h = conHandle(f)
  444. var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
  445. var numwrote: DWORD
  446. if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
  447. raiseOSError(osLastError())
  448. var origin = scrbuf.dwCursorPosition
  449. origin.x = 0'i16
  450. if setConsoleCursorPosition(h, origin) == 0:
  451. raiseOSError(osLastError())
  452. var wt: DWORD = scrbuf.dwSize.x - origin.x
  453. if fillConsoleOutputCharacter(h, ' ', wt,
  454. origin, addr(numwrote)) == 0:
  455. raiseOSError(osLastError())
  456. if fillConsoleOutputAttribute(h, scrbuf.wAttributes, wt,
  457. scrbuf.dwCursorPosition, addr(numwrote)) == 0:
  458. raiseOSError(osLastError())
  459. else:
  460. f.write("\e[2K")
  461. setCursorXPos(f, 0)
  462. proc eraseScreen*(f: File) =
  463. ## Erases the screen with the background colour and moves the cursor to home.
  464. when defined(windows):
  465. let h = conHandle(f)
  466. var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
  467. var numwrote: DWORD
  468. var origin: COORD # is inititalized to 0, 0
  469. if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
  470. raiseOSError(osLastError())
  471. let numChars = int32(scrbuf.dwSize.x)*int32(scrbuf.dwSize.y)
  472. if fillConsoleOutputCharacter(h, ' ', numChars,
  473. origin, addr(numwrote)) == 0:
  474. raiseOSError(osLastError())
  475. if fillConsoleOutputAttribute(h, scrbuf.wAttributes, numChars,
  476. origin, addr(numwrote)) == 0:
  477. raiseOSError(osLastError())
  478. setCursorXPos(f, 0)
  479. else:
  480. f.write("\e[2J")
  481. when not defined(windows):
  482. var
  483. gFG {.threadvar.}: int
  484. gBG {.threadvar.}: int
  485. proc resetAttributes*(f: File) =
  486. ## Resets all attributes.
  487. when defined(windows):
  488. let term = getTerminal()
  489. if f == stderr:
  490. discard setConsoleTextAttribute(term.hStderr, term.oldStderrAttr)
  491. else:
  492. discard setConsoleTextAttribute(term.hStdout, term.oldStdoutAttr)
  493. else:
  494. f.write(ansiResetCode)
  495. gFG = 0
  496. gBG = 0
  497. type
  498. Style* = enum ## Different styles for text output.
  499. styleBright = 1, ## bright text
  500. styleDim, ## dim text
  501. styleItalic, ## italic (or reverse on terminals not supporting)
  502. styleUnderscore, ## underscored text
  503. styleBlink, ## blinking/bold text
  504. styleBlinkRapid, ## rapid blinking/bold text (not widely supported)
  505. styleReverse, ## reverse
  506. styleHidden, ## hidden text
  507. styleStrikethrough ## strikethrough
  508. proc ansiStyleCode*(style: int): string =
  509. result = fmt"{stylePrefix}{style}m"
  510. template ansiStyleCode*(style: Style): string =
  511. ansiStyleCode(style.int)
  512. # The styleCache can be skipped when `style` is known at compile-time
  513. template ansiStyleCode*(style: static[Style]): string =
  514. (static(stylePrefix & $style.int & "m"))
  515. proc setStyle*(f: File, style: set[Style]) =
  516. ## Sets the terminal style.
  517. when defined(windows):
  518. let h = conHandle(f)
  519. var old = getAttributes(h) and (FOREGROUND_RGB or BACKGROUND_RGB)
  520. var a = 0'i16
  521. if styleBright in style: a = a or int16(FOREGROUND_INTENSITY)
  522. if styleBlink in style: a = a or int16(BACKGROUND_INTENSITY)
  523. if styleReverse in style: a = a or 0x4000'i16 # COMMON_LVB_REVERSE_VIDEO
  524. if styleUnderscore in style: a = a or 0x8000'i16 # COMMON_LVB_UNDERSCORE
  525. discard setConsoleTextAttribute(h, old or a)
  526. else:
  527. for s in items(style):
  528. f.write(ansiStyleCode(s))
  529. proc writeStyled*(txt: string, style: set[Style] = {styleBright}) =
  530. ## Writes the text `txt` in a given `style` to stdout.
  531. when defined(windows):
  532. let term = getTerminal()
  533. var old = getAttributes(term.hStdout)
  534. stdout.setStyle(style)
  535. stdout.write(txt)
  536. discard setConsoleTextAttribute(term.hStdout, old)
  537. else:
  538. stdout.setStyle(style)
  539. stdout.write(txt)
  540. stdout.resetAttributes()
  541. if gFG != 0:
  542. stdout.write(ansiStyleCode(gFG))
  543. if gBG != 0:
  544. stdout.write(ansiStyleCode(gBG))
  545. type
  546. ForegroundColor* = enum ## Terminal's foreground colors.
  547. fgBlack = 30, ## black
  548. fgRed, ## red
  549. fgGreen, ## green
  550. fgYellow, ## yellow
  551. fgBlue, ## blue
  552. fgMagenta, ## magenta
  553. fgCyan, ## cyan
  554. fgWhite, ## white
  555. fg8Bit, ## 256-color (not supported, see `enableTrueColors` instead.)
  556. fgDefault ## default terminal foreground color
  557. BackgroundColor* = enum ## Terminal's background colors.
  558. bgBlack = 40, ## black
  559. bgRed, ## red
  560. bgGreen, ## green
  561. bgYellow, ## yellow
  562. bgBlue, ## blue
  563. bgMagenta, ## magenta
  564. bgCyan, ## cyan
  565. bgWhite, ## white
  566. bg8Bit, ## 256-color (not supported, see `enableTrueColors` instead.)
  567. bgDefault ## default terminal background color
  568. when defined(windows):
  569. var defaultForegroundColor, defaultBackgroundColor: int16 = 0xFFFF'i16 # Default to an invalid value 0xFFFF
  570. proc setForegroundColor*(f: File, fg: ForegroundColor, bright = false) =
  571. ## Sets the terminal's foreground color.
  572. when defined(windows):
  573. let h = conHandle(f)
  574. var old = getAttributes(h) and not FOREGROUND_RGB
  575. if defaultForegroundColor == 0xFFFF'i16:
  576. defaultForegroundColor = old
  577. old = if bright: old or FOREGROUND_INTENSITY
  578. else: old and not(FOREGROUND_INTENSITY)
  579. const lookup: array[ForegroundColor, int] = [
  580. 0, # ForegroundColor enum with ordinal 30
  581. (FOREGROUND_RED),
  582. (FOREGROUND_GREEN),
  583. (FOREGROUND_RED or FOREGROUND_GREEN),
  584. (FOREGROUND_BLUE),
  585. (FOREGROUND_RED or FOREGROUND_BLUE),
  586. (FOREGROUND_BLUE or FOREGROUND_GREEN),
  587. (FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED),
  588. 0, # fg8Bit not supported, see `enableTrueColors` instead.
  589. 0] # unused
  590. if fg == fgDefault:
  591. discard setConsoleTextAttribute(h, cast[int16](cast[uint16](old) or cast[uint16](defaultForegroundColor)))
  592. else:
  593. discard setConsoleTextAttribute(h, cast[int16](cast[uint16](old) or cast[uint16](lookup[fg])))
  594. else:
  595. gFG = ord(fg)
  596. if bright: inc(gFG, 60)
  597. f.write(ansiStyleCode(gFG))
  598. proc setBackgroundColor*(f: File, bg: BackgroundColor, bright = false) =
  599. ## Sets the terminal's background color.
  600. when defined(windows):
  601. let h = conHandle(f)
  602. var old = getAttributes(h) and not BACKGROUND_RGB
  603. if defaultBackgroundColor == 0xFFFF'i16:
  604. defaultBackgroundColor = old
  605. old = if bright: old or BACKGROUND_INTENSITY
  606. else: old and not(BACKGROUND_INTENSITY)
  607. const lookup: array[BackgroundColor, int] = [
  608. 0, # BackgroundColor enum with ordinal 40
  609. (BACKGROUND_RED),
  610. (BACKGROUND_GREEN),
  611. (BACKGROUND_RED or BACKGROUND_GREEN),
  612. (BACKGROUND_BLUE),
  613. (BACKGROUND_RED or BACKGROUND_BLUE),
  614. (BACKGROUND_BLUE or BACKGROUND_GREEN),
  615. (BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED),
  616. 0, # bg8Bit not supported, see `enableTrueColors` instead.
  617. 0] # unused
  618. if bg == bgDefault:
  619. discard setConsoleTextAttribute(h, cast[int16](cast[uint16](old) or cast[uint16](defaultBackgroundColor)))
  620. else:
  621. discard setConsoleTextAttribute(h, cast[int16](cast[uint16](old) or cast[uint16](lookup[bg])))
  622. else:
  623. gBG = ord(bg)
  624. if bright: inc(gBG, 60)
  625. f.write(ansiStyleCode(gBG))
  626. proc ansiForegroundColorCode*(fg: ForegroundColor, bright = false): string =
  627. var style = ord(fg)
  628. if bright: inc(style, 60)
  629. return ansiStyleCode(style)
  630. template ansiForegroundColorCode*(fg: static[ForegroundColor],
  631. bright: static[bool] = false): string =
  632. ansiStyleCode(fg.int + bright.int * 60)
  633. proc ansiForegroundColorCode*(color: Color): string =
  634. let rgb = extractRGB(color)
  635. result = fmt"{fgPrefix}{rgb.r};{rgb.g};{rgb.b}m"
  636. template ansiForegroundColorCode*(color: static[Color]): string =
  637. const rgb = extractRGB(color)
  638. # no usage of `fmt`, see issue #7632
  639. (static("$1$2;$3;$4m" % [$fgPrefix, $(rgb.r), $(rgb.g), $(rgb.b)]))
  640. proc ansiBackgroundColorCode*(color: Color): string =
  641. let rgb = extractRGB(color)
  642. result = fmt"{bgPrefix}{rgb.r};{rgb.g};{rgb.b}m"
  643. template ansiBackgroundColorCode*(color: static[Color]): string =
  644. const rgb = extractRGB(color)
  645. # no usage of `fmt`, see issue #7632
  646. (static("$1$2;$3;$4m" % [$bgPrefix, $(rgb.r), $(rgb.g), $(rgb.b)]))
  647. proc setForegroundColor*(f: File, color: Color) =
  648. ## Sets the terminal's foreground true color.
  649. if getTerminal().trueColorIsEnabled:
  650. f.write(ansiForegroundColorCode(color))
  651. proc setBackgroundColor*(f: File, color: Color) =
  652. ## Sets the terminal's background true color.
  653. if getTerminal().trueColorIsEnabled:
  654. f.write(ansiBackgroundColorCode(color))
  655. proc setTrueColor(f: File, color: Color) =
  656. let term = getTerminal()
  657. if term.fgSetColor:
  658. setForegroundColor(f, color)
  659. else:
  660. setBackgroundColor(f, color)
  661. proc isatty*(f: File): bool =
  662. ## Returns true if `f` is associated with a terminal device.
  663. when defined(posix):
  664. proc isatty(fildes: FileHandle): cint {.
  665. importc: "isatty", header: "<unistd.h>".}
  666. else:
  667. proc isatty(fildes: FileHandle): cint {.
  668. importc: "_isatty", header: "<io.h>".}
  669. result = isatty(getFileHandle(f)) != 0'i32
  670. type
  671. TerminalCmd* = enum ## commands that can be expressed as arguments
  672. resetStyle, ## reset attributes
  673. fgColor, ## set foreground's true color
  674. bgColor ## set background's true color
  675. template styledEchoProcessArg(f: File, s: string) = write f, s
  676. template styledEchoProcessArg(f: File, style: Style) = setStyle(f, {style})
  677. template styledEchoProcessArg(f: File, style: set[Style]) = setStyle f, style
  678. template styledEchoProcessArg(f: File, color: ForegroundColor) =
  679. setForegroundColor f, color
  680. template styledEchoProcessArg(f: File, color: BackgroundColor) =
  681. setBackgroundColor f, color
  682. template styledEchoProcessArg(f: File, color: Color) =
  683. setTrueColor f, color
  684. template styledEchoProcessArg(f: File, cmd: TerminalCmd) =
  685. when cmd == resetStyle:
  686. resetAttributes(f)
  687. elif cmd in {fgColor, bgColor}:
  688. let term = getTerminal()
  689. term.fgSetColor = cmd == fgColor
  690. macro styledWrite*(f: File, m: varargs[typed]): untyped =
  691. ## Similar to `write`, but treating terminal style arguments specially.
  692. ## When some argument is `Style`, `set[Style]`, `ForegroundColor`,
  693. ## `BackgroundColor` or `TerminalCmd` then it is not sent directly to
  694. ## `f`, but instead corresponding terminal style proc is called.
  695. runnableExamples("-r:off"):
  696. stdout.styledWrite(fgRed, "red text ")
  697. stdout.styledWrite(fgGreen, "green text")
  698. var reset = false
  699. result = newNimNode(nnkStmtList)
  700. for i in countup(0, m.len - 1):
  701. let item = m[i]
  702. case item.kind
  703. of nnkStrLit..nnkTripleStrLit:
  704. if i == m.len - 1:
  705. # optimize if string literal is last, just call write
  706. result.add(newCall(bindSym"write", f, item))
  707. if reset: result.add(newCall(bindSym"resetAttributes", f))
  708. return
  709. else:
  710. # if it is string literal just call write, do not enable reset
  711. result.add(newCall(bindSym"write", f, item))
  712. else:
  713. result.add(newCall(bindSym"styledEchoProcessArg", f, item))
  714. reset = true
  715. if reset: result.add(newCall(bindSym"resetAttributes", f))
  716. template styledWriteLine*(f: File, args: varargs[untyped]) =
  717. ## Calls `styledWrite` and appends a newline at the end.
  718. runnableExamples:
  719. proc error(msg: string) =
  720. styledWriteLine(stderr, fgRed, "Error: ", resetStyle, msg)
  721. styledWrite(f, args)
  722. write(f, "\n")
  723. template styledEcho*(args: varargs[untyped]) =
  724. ## Echoes styles arguments to stdout using `styledWriteLine`.
  725. stdout.styledWriteLine(args)
  726. proc getch*(): char =
  727. ## Reads a single character from the terminal, blocking until it is entered.
  728. ## The character is not printed to the terminal.
  729. when defined(windows):
  730. let fd = getStdHandle(STD_INPUT_HANDLE)
  731. var keyEvent = KEY_EVENT_RECORD()
  732. var numRead: cint
  733. while true:
  734. # Block until character is entered
  735. doAssert(waitForSingleObject(fd, INFINITE) == WAIT_OBJECT_0)
  736. doAssert(readConsoleInput(fd, addr(keyEvent), 1, addr(numRead)) != 0)
  737. if numRead == 0 or keyEvent.eventType != 1 or keyEvent.bKeyDown == 0:
  738. continue
  739. return char(keyEvent.uChar)
  740. else:
  741. let fd = getFileHandle(stdin)
  742. var oldMode: Termios
  743. discard fd.tcGetAttr(addr oldMode)
  744. fd.setRaw()
  745. result = stdin.readChar()
  746. discard fd.tcSetAttr(TCSADRAIN, addr oldMode)
  747. when defined(windows):
  748. proc readPasswordFromStdin*(prompt: string, password: var string):
  749. bool {.tags: [ReadIOEffect, WriteIOEffect].} =
  750. ## Reads a `password` from stdin without printing it. `password` must not
  751. ## be `nil`! Returns `false` if the end of the file has been reached,
  752. ## `true` otherwise.
  753. password.setLen(0)
  754. stdout.write(prompt)
  755. let hi = createFileA("CONIN$",
  756. GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0)
  757. var mode = DWORD 0
  758. discard getConsoleMode(hi, addr mode)
  759. let origMode = mode
  760. const
  761. ENABLE_PROCESSED_INPUT = 1
  762. ENABLE_ECHO_INPUT = 4
  763. mode = (mode or ENABLE_PROCESSED_INPUT) and not ENABLE_ECHO_INPUT
  764. discard setConsoleMode(hi, mode)
  765. result = readLine(stdin, password)
  766. discard setConsoleMode(hi, origMode)
  767. discard closeHandle(hi)
  768. stdout.write "\n"
  769. else:
  770. import termios
  771. proc readPasswordFromStdin*(prompt: string, password: var string):
  772. bool {.tags: [ReadIOEffect, WriteIOEffect].} =
  773. password.setLen(0)
  774. let fd = stdin.getFileHandle()
  775. var cur, old: Termios
  776. discard fd.tcGetAttr(cur.addr)
  777. old = cur
  778. cur.c_lflag = cur.c_lflag and not Cflag(ECHO)
  779. discard fd.tcSetAttr(TCSADRAIN, cur.addr)
  780. stdout.write prompt
  781. result = stdin.readLine(password)
  782. stdout.write "\n"
  783. discard fd.tcSetAttr(TCSADRAIN, old.addr)
  784. proc readPasswordFromStdin*(prompt = "password: "): string =
  785. ## Reads a password from stdin without printing it.
  786. result = ""
  787. discard readPasswordFromStdin(prompt, result)
  788. # Wrappers assuming output to stdout:
  789. template hideCursor*() = hideCursor(stdout)
  790. template showCursor*() = showCursor(stdout)
  791. template setCursorPos*(x, y: int) = setCursorPos(stdout, x, y)
  792. template setCursorXPos*(x: int) = setCursorXPos(stdout, x)
  793. when defined(windows):
  794. template setCursorYPos*(x: int) = setCursorYPos(stdout, x)
  795. template cursorUp*(count = 1) = cursorUp(stdout, count)
  796. template cursorDown*(count = 1) = cursorDown(stdout, count)
  797. template cursorForward*(count = 1) = cursorForward(stdout, count)
  798. template cursorBackward*(count = 1) = cursorBackward(stdout, count)
  799. template eraseLine*() = eraseLine(stdout)
  800. template eraseScreen*() = eraseScreen(stdout)
  801. template setStyle*(style: set[Style]) =
  802. setStyle(stdout, style)
  803. template setForegroundColor*(fg: ForegroundColor, bright = false) =
  804. setForegroundColor(stdout, fg, bright)
  805. template setBackgroundColor*(bg: BackgroundColor, bright = false) =
  806. setBackgroundColor(stdout, bg, bright)
  807. template setForegroundColor*(color: Color) =
  808. setForegroundColor(stdout, color)
  809. template setBackgroundColor*(color: Color) =
  810. setBackgroundColor(stdout, color)
  811. proc resetAttributes*() {.noconv.} =
  812. ## Resets all attributes on stdout.
  813. ## It is advisable to register this as a quit proc with
  814. ## `exitprocs.addExitProc(resetAttributes)`.
  815. resetAttributes(stdout)
  816. proc isTrueColorSupported*(): bool =
  817. ## Returns true if a terminal supports true color.
  818. return getTerminal().trueColorIsSupported
  819. when defined(windows):
  820. import os
  821. proc enableTrueColors*() =
  822. ## Enables true color.
  823. var term = getTerminal()
  824. when defined(windows):
  825. var
  826. ver: OSVERSIONINFO
  827. ver.dwOSVersionInfoSize = sizeof(ver).DWORD
  828. let res = getVersionExW(addr ver)
  829. if res == 0:
  830. term.trueColorIsSupported = false
  831. else:
  832. term.trueColorIsSupported = ver.dwMajorVersion > 10 or
  833. (ver.dwMajorVersion == 10 and (ver.dwMinorVersion > 0 or
  834. (ver.dwMinorVersion == 0 and ver.dwBuildNumber >= 10586)))
  835. if not term.trueColorIsSupported:
  836. term.trueColorIsSupported = getEnv("ANSICON_DEF").len > 0
  837. if term.trueColorIsSupported:
  838. if getEnv("ANSICON_DEF").len == 0:
  839. var mode: DWORD = 0
  840. if getConsoleMode(getStdHandle(STD_OUTPUT_HANDLE), addr(mode)) != 0:
  841. mode = mode or ENABLE_VIRTUAL_TERMINAL_PROCESSING
  842. if setConsoleMode(getStdHandle(STD_OUTPUT_HANDLE), mode) != 0:
  843. term.trueColorIsEnabled = true
  844. else:
  845. term.trueColorIsEnabled = false
  846. else:
  847. term.trueColorIsEnabled = true
  848. else:
  849. term.trueColorIsSupported = getEnv("COLORTERM").toLowerAscii() in [
  850. "truecolor", "24bit"]
  851. term.trueColorIsEnabled = term.trueColorIsSupported
  852. proc disableTrueColors*() =
  853. ## Disables true color.
  854. var term = getTerminal()
  855. when defined(windows):
  856. if term.trueColorIsSupported:
  857. if getEnv("ANSICON_DEF").len == 0:
  858. var mode: DWORD = 0
  859. if getConsoleMode(getStdHandle(STD_OUTPUT_HANDLE), addr(mode)) != 0:
  860. mode = mode and not ENABLE_VIRTUAL_TERMINAL_PROCESSING
  861. discard setConsoleMode(getStdHandle(STD_OUTPUT_HANDLE), mode)
  862. term.trueColorIsEnabled = false
  863. else:
  864. term.trueColorIsEnabled = false
  865. proc newTerminal(): owned(PTerminal) =
  866. new result
  867. when defined(windows):
  868. initTerminal(result)