terminal.nim 33 KB

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