-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
writer.go
620 lines (495 loc) · 14.1 KB
/
writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
package terminal
import (
"fmt"
"os"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/mattn/go-runewidth"
)
func init() {
runewidth.DefaultCondition.EastAsianWidth = false
}
type style struct {
AnchorStart string
AnchorEnd string
Start string
End string
}
var (
knownStyles = []*style{
{AnchorStart: `<b>`, AnchorEnd: `</b>`, Start: "\x1b[1m", End: "\x1b[22m"},
{AnchorStart: `<u>`, AnchorEnd: `</u>`, Start: "\x1b[4m", End: "\x1b[24m"},
{AnchorStart: `<o>`, AnchorEnd: `</o>`, Start: "\x1b[53m", End: "\x1b[55m"},
{AnchorStart: `<i>`, AnchorEnd: `</i>`, Start: "\x1b[3m", End: "\x1b[23m"},
{AnchorStart: `<s>`, AnchorEnd: `</s>`, Start: "\x1b[9m", End: "\x1b[29m"},
{AnchorStart: `<d>`, AnchorEnd: `</d>`, Start: "\x1b[2m", End: "\x1b[22m"},
{AnchorStart: `<f>`, AnchorEnd: `</f>`, Start: "\x1b[5m", End: "\x1b[25m"},
{AnchorStart: `<r>`, AnchorEnd: `</r>`, Start: "\x1b[7m", End: "\x1b[27m"},
}
resetStyle = &style{AnchorStart: "RESET", AnchorEnd: `</>`, End: "\x1b[0m"}
backgroundStyle = &style{AnchorStart: "BACKGROUND", AnchorEnd: `</>`, End: "\x1b[49m"}
BackgroundColor color.Ansi
CurrentColors *color.Set
ParentColors []*color.Set
Colors color.String
Plain bool
Interactive bool
builder strings.Builder
length int
foregroundColor color.Ansi
backgroundColor color.Ansi
currentColor color.History
runes []rune
isTransparent bool
isInvisible bool
isHyperlink bool
Shell string
Program string
formats *shell.Formats
)
const (
AnchorRegex = `^(?P<ANCHOR><(?P<FG>[^,<>]+)?,?(?P<BG>[^<>]+)?>)`
colorise = "\x1b[%sm"
transparentStart = "\x1b[0m\x1b[%s;49m\x1b[7m"
transparentEnd = "\x1b[27m"
backgroundEnd = "\x1b[49m"
AnsiRegex = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
OSC99 = "osc99"
OSC7 = "osc7"
OSC51 = "osc51"
ANCHOR = "ANCHOR"
BG = "BG"
FG = "FG"
hyperLinkStart = "<LINK>"
hyperLinkEnd = "</LINK>"
hyperLinkText = "<TEXT>"
hyperLinkTextEnd = "</TEXT>"
empty = "<>"
startProgress = "\x1b]9;4;3;0\x07"
endProgress = "\x1b]9;4;0;0\x07"
WindowsTerminal = "Windows Terminal"
Warp = "WarpTerminal"
ITerm = "iTerm.app"
AppleTerminal = "Apple_Terminal"
Unknown = "Unknown"
)
func Init(sh string) {
Shell = sh
Program = getTerminalName()
log.Debug("terminal program:", Program)
log.Debug("terminal shell:", Shell)
color.TrueColor = Program != AppleTerminal
formats = shell.GetFormats(Shell)
}
func getTerminalName() string {
Program = os.Getenv("TERM_PROGRAM")
if len(Program) != 0 {
return Program
}
wtSession := os.Getenv("WT_SESSION")
if len(wtSession) != 0 {
return WindowsTerminal
}
return Unknown
}
func SetColors(background, foreground color.Ansi) {
CurrentColors = &color.Set{
Background: background,
Foreground: foreground,
}
}
func SetParentColors(background, foreground color.Ansi) {
if ParentColors == nil {
ParentColors = make([]*color.Set, 0)
}
ParentColors = append([]*color.Set{{
Background: background,
Foreground: foreground,
}}, ParentColors...)
}
func ChangeLine(numberOfLines int) string {
if Plain {
return ""
}
position := "B"
if numberOfLines < 0 {
position = "F"
numberOfLines = -numberOfLines
}
return fmt.Sprintf(formats.Linechange, numberOfLines, position)
}
func Pwd(pwdType, userName, hostName, pwd string) string {
if Plain {
return ""
}
switch pwdType {
case OSC7:
return fmt.Sprintf(formats.Osc7, hostName, pwd)
case OSC51:
return fmt.Sprintf(formats.Osc51, userName, hostName, pwd)
case OSC99:
fallthrough
default:
return fmt.Sprintf(formats.Osc99, pwd)
}
}
func ClearAfter() string {
if Plain {
return ""
}
return formats.ClearLine + formats.ClearBelow
}
func FormatTitle(title string) string {
switch Shell {
// These shells don't support setting the console title.
case shell.ELVISH, shell.XONSH, shell.TCSH:
return ""
case shell.BASH, shell.ZSH:
title = trimAnsi(title)
s := new(strings.Builder)
// We have to do this to prevent the shell from misidentifying escape sequences.
for _, char := range title {
escaped, shouldEscape := formats.EscapeSequences[char]
if shouldEscape {
s.WriteString(escaped)
continue
}
s.WriteRune(char)
}
return fmt.Sprintf(formats.Title, s.String())
default:
return fmt.Sprintf(formats.Title, trimAnsi(title))
}
}
func EscapeText(text string) string {
return fmt.Sprintf(formats.Escape, text)
}
func SaveCursorPosition() string {
return formats.SaveCursorPosition
}
func RestoreCursorPosition() string {
return formats.RestoreCursorPosition
}
func PromptStart() string {
return fmt.Sprintf(formats.Escape, "\x1b]133;A\007")
}
func CommandStart() string {
return fmt.Sprintf(formats.Escape, "\x1b]133;B\007")
}
func CommandFinished(code int, ignore bool) string {
if ignore {
return fmt.Sprintf(formats.Escape, "\x1b]133;D\007")
}
mark := fmt.Sprintf("\x1b]133;D;%d\007", code)
return fmt.Sprintf(formats.Escape, mark)
}
func LineBreak() string {
cr := fmt.Sprintf(formats.Left, 1000)
lf := fmt.Sprintf(formats.Linechange, 1, "B")
return cr + lf
}
func StartProgress() string {
if Program != WindowsTerminal {
return ""
}
return startProgress
}
func StopProgress() string {
if Program != WindowsTerminal {
return ""
}
return endProgress
}
func Write(background, foreground color.Ansi, text string) {
if len(text) == 0 {
return
}
backgroundColor, foregroundColor = asAnsiColors(background, foreground)
// default to white foreground
if foregroundColor.IsEmpty() {
foregroundColor = Colors.ToAnsi("white", false)
}
// validate if we start with a color override
match := regex.FindNamedRegexMatch(AnchorRegex, text)
if len(match) != 0 && match[ANCHOR] != hyperLinkStart {
colorOverride := true
for _, style := range knownStyles {
if match[ANCHOR] != style.AnchorStart {
continue
}
writeEscapedAnsiString(style.Start)
colorOverride = false
}
if colorOverride {
currentColor.Add(asAnsiColors(color.Ansi(match[BG]), color.Ansi(match[FG])))
}
}
writeSegmentColors()
// print the hyperlink part AFTER the coloring
if match[ANCHOR] == hyperLinkStart {
isHyperlink = true
builder.WriteString(formats.HyperlinkStart)
}
text = text[len(match[ANCHOR]):]
runes = []rune(text)
hyperlinkTextPosition := 0
for i := 0; i < len(runes); i++ {
s := runes[i]
// ignore everything which isn't overriding
if s != '<' {
write(s)
continue
}
// color/end overrides first
text = string(runes[i:])
match = regex.FindNamedRegexMatch(AnchorRegex, text)
if len(match) > 0 {
// check for hyperlinks first
switch match[ANCHOR] {
case hyperLinkStart:
isHyperlink = true
i += len([]rune(match[ANCHOR])) - 1
builder.WriteString(formats.HyperlinkStart)
continue
case hyperLinkText:
isHyperlink = false
i += len([]rune(match[ANCHOR])) - 1
hyperlinkTextPosition = i
builder.WriteString(formats.HyperlinkCenter)
continue
case hyperLinkTextEnd:
// this implies there's no text in the hyperlink
if hyperlinkTextPosition+1 == i {
builder.WriteString("link")
length += 4
}
i += len([]rune(match[ANCHOR])) - 1
continue
case hyperLinkEnd:
i += len([]rune(match[ANCHOR])) - 1
builder.WriteString(formats.HyperlinkEnd)
continue
case empty:
i += len([]rune(match[ANCHOR])) - 1
continue
}
i = writeArchorOverride(match, background, i)
continue
}
write(s)
}
// reset colors
writeEscapedAnsiString(resetStyle.End)
// pop last color from the stack
currentColor.Pop()
}
func String() (string, int) {
defer func() {
length = 0
builder.Reset()
isTransparent = false
isInvisible = false
}()
return builder.String(), length
}
func writeEscapedAnsiString(text string) {
if Plain {
return
}
if len(formats.Escape) != 0 {
text = fmt.Sprintf(formats.Escape, text)
}
builder.WriteString(text)
}
func getAnsiFromColorString(colorString color.Ansi, isBackground bool) color.Ansi {
return Colors.ToAnsi(colorString, isBackground)
}
func write(s rune) {
if isInvisible {
return
}
if isHyperlink {
builder.WriteRune(s)
return
}
// UNSOLVABLE: When "Interactive" is true, the prompt length calculation in Bash/Zsh can be wrong, since the final string expansion is done by shells.
length += runewidth.RuneWidth(s)
// length += utf8.RuneCountInString(string(s))
if !Interactive && !Plain {
escaped, shouldEscape := formats.EscapeSequences[s]
if shouldEscape {
builder.WriteString(escaped)
return
}
}
builder.WriteRune(s)
}
func writeSegmentColors() {
// use correct starting colors
bg := backgroundColor
fg := foregroundColor
if !currentColor.Background().IsEmpty() {
bg = currentColor.Background()
}
if !currentColor.Foreground().IsEmpty() {
fg = currentColor.Foreground()
}
// ignore processing fully tranparent colors
isInvisible = fg.IsTransparent() && bg.IsTransparent()
if isInvisible {
return
}
if fg.IsTransparent() && len(BackgroundColor) != 0 { //nolint: gocritic
background := getAnsiFromColorString(BackgroundColor, false)
writeEscapedAnsiString(fmt.Sprintf(colorise, background))
writeEscapedAnsiString(fmt.Sprintf(colorise, bg.ToForeground()))
} else if fg.IsTransparent() && !bg.IsEmpty() {
isTransparent = true
writeEscapedAnsiString(fmt.Sprintf(transparentStart, bg))
} else {
if !bg.IsEmpty() && !bg.IsTransparent() {
writeEscapedAnsiString(fmt.Sprintf(colorise, bg))
}
if !fg.IsEmpty() {
writeEscapedAnsiString(fmt.Sprintf(colorise, fg))
}
}
// set current colors
currentColor.Add(bg, fg)
}
func writeArchorOverride(match map[string]string, background color.Ansi, i int) int {
position := i
// check color reset first
if match[ANCHOR] == resetStyle.AnchorEnd {
return endColorOverride(position)
}
position += len([]rune(match[ANCHOR])) - 1
for _, style := range knownStyles {
if style.AnchorEnd == match[ANCHOR] {
writeEscapedAnsiString(style.End)
return position
}
if style.AnchorStart == match[ANCHOR] {
writeEscapedAnsiString(style.Start)
return position
}
}
bgColor := color.Ansi(match[BG])
fgColor := color.Ansi(match[FG])
if fgColor.IsTransparent() && bgColor.IsEmpty() {
bgColor = background
}
bg, fg := asAnsiColors(bgColor, fgColor)
// ignore processing fully tranparent colors
isInvisible = fg.IsTransparent() && bg.IsTransparent()
if isInvisible {
return position
}
// make sure we have colors
if fg.IsEmpty() {
fg = foregroundColor
}
if bg.IsEmpty() {
bg = backgroundColor
}
currentColor.Add(bg, fg)
if currentColor.Foreground().IsTransparent() && len(BackgroundColor) != 0 {
background := getAnsiFromColorString(BackgroundColor, false)
writeEscapedAnsiString(fmt.Sprintf(colorise, background))
writeEscapedAnsiString(fmt.Sprintf(colorise, currentColor.Background().ToForeground()))
return position
}
if currentColor.Foreground().IsTransparent() && !currentColor.Background().IsTransparent() {
isTransparent = true
writeEscapedAnsiString(fmt.Sprintf(transparentStart, currentColor.Background()))
return position
}
if currentColor.Background() != backgroundColor {
// end the colors in case we have a transparent background
if currentColor.Background().IsTransparent() {
writeEscapedAnsiString(backgroundEnd)
} else {
writeEscapedAnsiString(fmt.Sprintf(colorise, currentColor.Background()))
}
}
if currentColor.Foreground() != foregroundColor {
writeEscapedAnsiString(fmt.Sprintf(colorise, currentColor.Foreground()))
}
return position
}
func endColorOverride(position int) int {
// make sure to reset the colors if needed
position += len([]rune(resetStyle.AnchorEnd)) - 1
// do not restore colors at the end of the string, we print it anyways
if position == len(runes)-1 {
currentColor.Pop()
return position
}
// reset colors to previous when we have more than 1 in stack
// as soon as we have more than 1, we can pop the last one
// and print the previous override as it wasn't ended yet
if currentColor.Len() > 1 {
fg := currentColor.Foreground()
bg := currentColor.Background()
currentColor.Pop()
previousBg := currentColor.Background()
previousFg := currentColor.Foreground()
if isTransparent {
writeEscapedAnsiString(transparentEnd)
}
if previousBg != bg {
background := fmt.Sprintf(colorise, previousBg)
if previousBg.IsClear() {
background = backgroundStyle.End
}
writeEscapedAnsiString(background)
}
if previousFg != fg {
writeEscapedAnsiString(fmt.Sprintf(colorise, previousFg))
}
return position
}
// pop the last colors from the stack
defer currentColor.Pop()
// do not reset when colors are identical
if currentColor.Background() == backgroundColor && currentColor.Foreground() == foregroundColor {
return position
}
if isTransparent {
writeEscapedAnsiString(transparentEnd)
}
if backgroundColor.IsClear() {
writeEscapedAnsiString(backgroundStyle.End)
}
if currentColor.Background() != backgroundColor && !backgroundColor.IsClear() {
writeEscapedAnsiString(fmt.Sprintf(colorise, backgroundColor))
}
if (currentColor.Foreground() != foregroundColor || isTransparent) && !foregroundColor.IsClear() {
writeEscapedAnsiString(fmt.Sprintf(colorise, foregroundColor))
}
isTransparent = false
return position
}
func asAnsiColors(background, foreground color.Ansi) (color.Ansi, color.Ansi) {
if len(background) == 0 {
background = color.Background
}
if len(foreground) == 0 {
foreground = color.Foreground
}
background = background.Resolve(CurrentColors, ParentColors)
foreground = foreground.Resolve(CurrentColors, ParentColors)
inverted := foreground == color.Transparent && len(background) != 0
backgroundAnsi := getAnsiFromColorString(background, !inverted)
foregroundAnsi := getAnsiFromColorString(foreground, false)
return backgroundAnsi, foregroundAnsi
}
func trimAnsi(text string) string {
if len(text) == 0 || !strings.Contains(text, "\x1b") {
return text
}
return regex.ReplaceAllString(AnsiRegex, text, "")
}