Repository navigation
Expand file tree
/
Copy pathconvert-omp.py
More file actions
2449 lines (2277 loc) · 112 KB
/
Copy pathconvert-omp.py
File metadata and controls
2449 lines (2277 loc) · 112 KB
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Nirmana-Shell - Oh My Posh to Starship Theme Transpiler (Version 3.1)
Converts Oh My Posh theme JSON configurations (*.omp.json) into clean,
high-performance Starship themes (*.toml) with zero-seam powerline ribbons,
resilient dual-capsule left prompts, multi-line block fidelity, and full
support for modern Starship features (such as prev_bg from PR #6017).
"""
import argparse
import glob
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
GO_DATE_TO_STRFTIME = [
("Monday", "%A"),
("Mon", "%a"),
("January", "%B"),
("Jan", "%b"),
("2006", "%Y"),
("06", "%y"),
("01", "%m"),
("1", "%m"),
("02", "%d"),
("2", "%d"),
("15", "%H"),
("03", "%I"),
("3", "%I"),
("04", "%M"),
("4", "%M"),
("05", "%S"),
("5", "%S"),
("PM", "%p"),
("pm", "%p"),
("MST", "%Z"),
]
OMP_COLOR_MAP = {
"lightyellow": "#FFF59D",
"lightblue": "#80D8FF",
"lightgreen": "#A5D6A7",
"lightcyan": "#80DEEA",
"lightmagenta": "#F48FB1",
"lightred": "#FF8A80",
"lightwhite": "#FFFFFF",
"lightblack": "#757575",
"darkgray": "#616161",
"darkgrey": "#616161",
"gray": "#9E9E9E",
"grey": "#9E9E9E",
"darkred": "#C62828",
"darkgreen": "#2E7D32",
"darkblue": "#1565C0",
"darkcyan": "#00838F",
"darkmagenta": "#6A1B9A",
"darkyellow": "#F9A825",
"white": "#FFFFFF",
"black": "#000000",
"red": "#FF5252",
"green": "#69F0AE",
"blue": "#448AFF",
"yellow": "#FFD740",
"magenta": "#FF4081",
"cyan": "#18FFFF",
}
RUNTIME_MAPPINGS = {
"node": ("nodejs", "$nodejs", " ", "#80D166"),
"nodejs": ("nodejs", "$nodejs", " ", "#80D166"),
"go": ("golang", "$golang", " ", "#06AAD5"),
"golang": ("golang", "$golang", " ", "#06AAD5"),
"python": ("python", "$python", " ", "#FFE873"),
"rust": ("rust", "$rust", " ", "#F78C6C"),
"ruby": ("ruby", "$ruby", " ", "#FF5874"),
"java": ("java", "$java", " ", "#EC2729"),
"dotnet": ("dotnet", "$dotnet", " ", "#0D6DA8"),
"php": ("php", "$php", " ", "#787CB5"),
"bun": ("bun", "$bun", " ", "#FF9F43"),
"deno": ("deno", "$deno", " ", "#7FD5EA"),
"dart": ("dart", "$dart", " ", "#7FD5EA"),
"julia": ("julia", "$julia", " ", "#945BB3"),
"package": ("package", "$package", " ", "#AEA4BF"),
"c": ("c", "$c", " ", "#00599C"),
"cpp": ("cpp", "$cpp", " ", "#00599C"),
"kotlin": ("kotlin", "$kotlin", " ", "#F18E33"),
"scala": ("scala", "$scala", " ", "#DC322F"),
"haskell": ("haskell", "$haskell", " ", "#5E5086"),
"elixir": ("elixir", "$elixir", " ", "#4E2A8E"),
"elm": ("elm", "$elm", " ", "#60B5CC"),
"erlang": ("erlang", "$erlang", " ", "#A90533"),
"lua": ("lua", "$lua", " ", "#000080"),
"zig": ("zig", "$zig", " ", "#F7A41D"),
"nim": ("nim", "$nim", " ", "#FFE953"),
"crystal": ("crystal", "$crystal", " ", "#000000"),
"docker": ("docker_context", "$docker_context", " ", "#2496ED"),
"docker_context": ("docker_context", "$docker_context", " ", "#2496ED"),
"kubernetes": ("kubernetes", "$kubernetes", " ", "#326CE5"),
"terraform": ("terraform", "$terraform", " ", "#844FBA"),
"aws": ("aws", "$aws", " ", "#FF9900"),
"az": ("azure", "$azure", " ", "#008AD7"),
"azure": ("azure", "$azure", " ", "#008AD7"),
"gcloud": ("gcloud", "$gcloud", " ", "#4285F4"),
"conda": ("conda", "$conda", " ", "#44A833"),
}
STANDARD_DEVELOPER_RUNTIMES = [
("nodejs", "$nodejs", " ", "#80D166"),
("python", "$python", " ", "#FFE873"),
("golang", "$golang", " ", "#06AAD5"),
("rust", "$rust", " ", "#F78C6C"),
("php", "$php", " ", "#787CB5"),
("package", "$package", " ", "#AEA4BF"),
]
OMP_UPSTREAM_REPOSITORY = "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh"
DEFAULT_OMP_MANIFEST = Path(__file__).with_name("omp-themes.txt")
def convert_go_date_format(go_fmt: str) -> str:
"""Convert Go time reference format to strftime format."""
res = re.sub(r"<[^>]+>", "", go_fmt)
for go_pat, strftime_pat in GO_DATE_TO_STRFTIME:
res = re.sub(r"\b" + re.escape(go_pat) + r"\b", strftime_pat, res)
return res
def normalize_omp_template(text: Optional[str]) -> str:
"""Resolve static Go template control flow and remove unsupported actions."""
if not text:
return ""
normalized = text
conditional = re.compile(
r"\{\{\s*if\b[^}]*\}\}(.*?)\{\{\s*else\s*\}\}(.*?)\{\{\s*end\s*\}\}",
re.DOTALL,
)
while conditional.search(normalized):
normalized = conditional.sub(lambda match: match.group(2), normalized)
normalized = re.sub(
r"\{\{\s*(?:if|with|range)\b[^}]*\}\}.*?\{\{\s*end\s*\}\}",
"",
normalized,
flags=re.DOTALL,
)
return re.sub(r"\{\{.*?\}\}", "", normalized)
def parse_omp_markup(text: Optional[str], default_fg: Optional[str] = None) -> str:
"""Convert Oh My Posh diamond/template markup (<#hex>text</>) to Starship styled spans."""
if not text:
return ""
cleaned = normalize_omp_template(text)
if not cleaned.strip():
return ""
spans = []
pos = 0
pattern = re.compile(r"<([#a-zA-Z0-9_\-]+)>(.*?)</>")
for m in pattern.finditer(cleaned):
if m.start() > pos:
plain = re.sub(r"<[^>]+>", "", cleaned[pos:m.start()])
if plain:
fg_spec = f"bold {default_fg}" if default_fg else "bold"
spans.append(f"[{plain}]({fg_spec})")
col = m.group(1)
content = m.group(2)
if content:
spans.append(f"[{content}](bold {col})")
pos = m.end()
if pos < len(cleaned):
plain = re.sub(r"<[^>]+>", "", cleaned[pos:])
if plain:
fg_spec = f"bold {default_fg}" if default_fg else "bold"
spans.append(f"[{plain}]({fg_spec})")
return "".join(spans)
def parse_omp_json(source: str, upstream_ref: str = "main") -> Tuple[Dict[str, Any], str]:
"""Load JSON from local file, remote URL, or Oh My Posh official theme name."""
theme_name = ""
url = source
if not source.startswith("http://") and not source.startswith("https://"):
path = Path(source)
if not path.exists():
candidate_name = source.replace(".omp.json", "").replace(".json", "")
encoded_ref = urllib.parse.quote(upstream_ref, safe="")
encoded_name = urllib.parse.quote(candidate_name, safe="._-")
url = f"{OMP_UPSTREAM_REPOSITORY}/{encoded_ref}/themes/{encoded_name}.omp.json"
theme_name = candidate_name
else:
data = path.read_text(encoding="utf-8")
theme_name = path.stem.replace(".omp", "")
return json.loads(data), theme_name
if url.startswith("http://") or url.startswith("https://"):
req = urllib.request.Request(
url,
headers={"User-Agent": "Nirmana-Shell-Transpiler/3.1"},
)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
data = resp.read().decode("utf-8")
if not theme_name:
theme_name = Path(url.split("?")[0]).stem.replace(".omp", "")
return json.loads(data), theme_name
except Exception as e:
print(f"Error fetching Oh My Posh theme '{source}': {e}", file=sys.stderr)
sys.exit(1)
def load_theme_manifest(manifest_path: Path) -> List[str]:
"""Read the maintained list of upstream Oh My Posh themes to transpile."""
if not manifest_path.is_file():
raise FileNotFoundError(f"Theme manifest not found: {manifest_path}")
themes: List[str] = []
for line_number, raw_line in enumerate(manifest_path.read_text(encoding="utf-8").splitlines(), start=1):
theme_name = raw_line.strip()
if not theme_name or theme_name.startswith("#"):
continue
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", theme_name):
raise ValueError(f"Invalid theme name at {manifest_path}:{line_number}: {theme_name}")
themes.append(theme_name)
if not themes:
raise ValueError(f"Theme manifest is empty: {manifest_path}")
if len(themes) != len(set(themes)):
raise ValueError(f"Theme manifest contains duplicate entries: {manifest_path}")
return themes
class OmpTranspiler:
def __init__(
self,
data: Dict[str, Any],
theme_name: str,
use_fill: bool = True,
left_style_override: Optional[str] = None,
use_pills: bool = False,
ribbon_bg_override: Optional[str] = None,
add_runtimes: bool = True,
force_runtimes: bool = False,
):
self.data = data
self.theme_name = theme_name
self.use_fill = use_fill
self.left_style_override = left_style_override
self.use_pills = use_pills
self.ribbon_bg_override = ribbon_bg_override
self.add_runtimes = add_runtimes
self.force_runtimes = force_runtimes
self.palette = data.get("palette", {})
self.modules: Dict[str, Dict[str, Any]] = {}
self.has_top_connector = False
self.char_is_plain = False
def resolve_color(self, col: Optional[str]) -> Optional[str]:
"""Resolve hex, named, or palette-referenced colors to clean hex strings."""
if not col:
return None
col = str(col).strip()
if col.lower() == "transparent":
return None
if col.startswith("p:"):
key = col[2:]
col = self.palette.get(key, key)
elif col in self.palette:
col = self.palette[col]
if not col or str(col).strip().lower() == "transparent":
return None
c_lower = str(col).strip().lower()
if c_lower in OMP_COLOR_MAP:
return OMP_COLOR_MAP[c_lower]
h = col[1:] if col.startswith("#") else col
if len(h) == 3 and all(c in "0123456789abcdefABCDEF" for c in h):
return f"#{h[0]*2}{h[1]*2}{h[2]*2}"
elif len(h) == 6 and all(c in "0123456789abcdefABCDEF" for c in h):
return f"#{h}"
elif len(h) == 8 and all(c in "0123456789abcdefABCDEF" for c in h):
return f"#{h[:6]}"
return col
def get_seg_colors(self, seg: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]:
"""Extract foreground and background colors with template fallback support."""
fg = self.resolve_color(seg.get("foreground"))
bg = self.resolve_color(seg.get("background"))
if not bg and "background_templates" in seg:
for bt in seg["background_templates"]:
m = re.search(r"(?:#([0-9a-fA-F]{3,6})|p:([a-zA-Z0-9_\-]+))", bt)
if m:
bg = self.resolve_color(f"#{m.group(1)}" if m.group(1) else f"p:{m.group(2)}")
if bg:
break
if not fg and "foreground_templates" in seg:
for ft in seg["foreground_templates"]:
m = re.search(r"(?:#([0-9a-fA-F]{3,6})|p:([a-zA-Z0-9_\-]+))", ft)
if m:
fg = self.resolve_color(f"#{m.group(1)}" if m.group(1) else f"p:{m.group(2)}")
if fg:
break
return fg, bg
def transpile(self) -> str:
blocks = self.data.get("blocks", [])
if not blocks:
return ""
all_segs = [s for b in blocks for s in b.get("segments", [])]
# Step 1: Detect Overall Theme Visual Style
has_any_bg = any(self.get_seg_colors(s)[1] is not None for s in all_segs)
has_bracket_frame = any(
any(c in s.get("template", "") for c in ("\u250f", "┏", "\u2514", "┗", "\u2516", "┖"))
for s in all_segs
)
has_rounded_powerline = any(s.get("powerline_symbol") == "\ue0b4" for s in all_segs)
pixel_powerline_count = sum(
1 for s in all_segs
if s.get("powerline_symbol") in ("\ue0c4", "\ue0c5") or
any(g in (s.get("leading_diamond", "") + s.get("trailing_diamond", "")) for g in ("\ue0c6", "\ue0c7"))
)
rounded_powerline_count = sum(1 for s in all_segs if s.get("powerline_symbol") == "\ue0b4")
has_pixel_powerline = pixel_powerline_count > 0 and pixel_powerline_count >= rounded_powerline_count
is_flat_ribbon = False
if len(all_segs) >= 3 and not has_rounded_powerline and not has_pixel_powerline:
b0_segs = blocks[0].get("segments", []) if blocks else []
if b0_segs and b0_segs[0].get("leading_diamond") == "\ue0b6":
plain_bg_count = sum(1 for s in b0_segs[1:] if s.get("style") == "plain" and self.get_seg_colors(s)[1])
if plain_bg_count >= 2:
is_flat_ribbon = True
powerline_count = sum(
1 for s in all_segs
if any(g in (s.get("leading_diamond", "") + s.get("trailing_diamond", "") + s.get("powerline_symbol", "") + s.get("template", "")) for g in ("\ue0b0", "\ue0b2", "\ue0b1", "\ue0b3", "\ue0c4", "\ue0c5", "\ue0c0", "\ue0c2"))
)
capsule_count = sum(
1 for s in all_segs
if any(g in (s.get("leading_diamond", "") + s.get("trailing_diamond", "")) for g in ("\ue0b6", "\ue0b4"))
)
has_pill_diamonds = sum(
1 for s in all_segs
if "\ue0b6" in s.get("leading_diamond", "") and "\ue0b4" in s.get("trailing_diamond", "")
) >= 2
self.has_top_connector = any(
any(c in (s.get("leading_diamond", "") + s.get("template", "")) for c in ("\u256d", "╭"))
for s in all_segs
)
self.powerline_symbol = "\ue0b0"
self.has_bracket_frame = has_bracket_frame
self.bracket_fg = "#CB4B16"
if has_bracket_frame:
for s in all_segs:
m_b = re.search(r"<([#a-zA-Z0-9_\-]+)>[┏┖┗\u250f\u2514\u2516\[]", s.get("template", ""))
if m_b:
self.bracket_fg = self.resolve_color(m_b.group(1)) or self.bracket_fg
break
theme_style = "bracket_frame"
self.use_fill = False
elif has_pixel_powerline:
theme_style = "powerline"
self.powerline_symbol = "\ue0c4"
elif has_rounded_powerline:
theme_style = "powerline"
self.powerline_symbol = "\ue0b4"
elif is_flat_ribbon:
theme_style = "powerline"
self.powerline_symbol = ""
elif not has_any_bg:
theme_style = "flat"
elif has_pill_diamonds:
theme_style = "capsule"
elif powerline_count >= capsule_count and powerline_count > 0:
theme_style = "powerline"
self.powerline_symbol = "\ue0b0"
elif capsule_count > 0:
theme_style = "capsule"
else:
theme_style = "capsule" if has_any_bg else "flat"
if self.left_style_override:
theme_style = self.left_style_override
# Step 2: Group blocks into physical lines
has_block_diamonds = any(b.get("leading_diamond") for b in blocks)
if has_block_diamonds:
self.use_fill = False
prompt_lines: List[Dict[str, List[Dict[str, Any]]]] = []
if has_block_diamonds:
# Group framed blocks by level:
# Level 0 (Header): blocks with ┏ or ╭
# Level 1 (Body): all intermediate blocks (sharing ┣ or │), combining path, git, cloud, runtimes
# Level 2 (Footer): block with └ or ╰ (character line)
header_segs = []
body_segs = []
footer_segs = []
header_lead = ""
body_lead = ""
footer_lead = ""
for b in blocks:
lead_dia = b.get("leading_diamond", "")
lead_markup = parse_omp_markup(lead_dia) if lead_dia else ""
segs = list(b.get("segments", []))
if any(c in lead_dia for c in ("\u250f", "┏", "\u256d", "╭")):
if not header_lead:
header_lead = lead_markup
header_segs.extend(segs)
elif any(c in lead_dia for c in ("\u2514", "└", "\u2570", "╰")):
if not footer_lead:
footer_lead = lead_markup
footer_segs.extend(segs)
else:
if not body_lead and lead_markup:
body_lead = lead_markup
body_segs.extend(segs)
# Insert connectors at the start of each line
if header_lead:
header_segs.insert(0, {"type": "block_connector", "markup": header_lead})
if body_lead:
body_segs.insert(0, {"type": "block_connector", "markup": body_lead})
if footer_lead:
footer_segs.insert(0, {"type": "block_connector", "markup": footer_lead})
# Ensure navigation (path/git) comes before cloud/tool segments on body line if present
nav_segs = [s for s in body_segs if s.get("type") in ("path", "git")]
other_segs = [s for s in body_segs if s.get("type") not in ("path", "git", "block_connector")]
conn_seg = [s for s in body_segs if s.get("type") == "block_connector"]
body_segs = conn_seg + nav_segs + other_segs
prompt_lines.append({"left": header_segs, "right": []})
if body_segs:
prompt_lines.append({"left": body_segs, "right": []})
if footer_segs:
prompt_lines.append({"left": footer_segs, "right": []})
else:
curr_line: Dict[str, List[Dict[str, Any]]] = {"left": [], "right": []}
for idx, b in enumerate(blocks):
lead_dia = b.get("leading_diamond")
lead_markup = parse_omp_markup(lead_dia) if lead_dia else ""
if idx > 0 and b.get("newline"):
prompt_lines.append(curr_line)
curr_line = {"left": [], "right": []}
align = b.get("alignment", "left")
if b.get("type") == "rprompt":
align = "right"
segs = list(b.get("segments", []))
if lead_markup and align == "left":
segs.insert(0, {"type": "block_connector", "markup": lead_markup})
curr_line[align].extend(segs)
prompt_lines.append(curr_line)
# OMP Rule: If a line has NO left-aligned segments, right-aligned blocks render as left-aligned!
for pl in prompt_lines:
if not pl["left"] and pl["right"]:
pl["left"] = pl["right"]
pl["right"] = []
# Guard: If line 1 left is empty but line 1 right contains navigation/identity modules, relocate to left
nav_types = ("path", "git", "os", "root")
if not prompt_lines[0]["left"]:
nav_segs = [s for s in prompt_lines[0]["right"] if s.get("type") in nav_types]
if nav_segs:
prompt_lines[0]["left"].extend(nav_segs)
prompt_lines[0]["right"] = [s for s in prompt_lines[0]["right"] if s.get("type") not in nav_types]
is_single_line = len(prompt_lines) <= 1
self.is_single_line = is_single_line
# Dedup modules between lines in multi-line prompts (e.g. cloud-context)
if len(prompt_lines) > 1:
later_types = set()
for pl in prompt_lines[1:]:
for s in pl["left"]:
st = s.get("type")
if st in ("git", "time", "path"):
later_types.add(st)
prompt_lines[0]["left"] = [s for s in prompt_lines[0]["left"] if s.get("type") not in later_types]
if len(prompt_lines) >= 3 and any(s.get("type") == "path" for s in prompt_lines[1]["left"]):
prompt_lines[1]["left"] = [s for s in prompt_lines[1]["left"] if s.get("type") != "time"]
# Step 3: Extract prompt character from the last line (status or text segment)
line_character = None
has_pill_prompt_user = False
last_left = prompt_lines[-1]["left"] if prompt_lines else []
connector_span = ""
for s in list(last_left):
stype = s.get("type")
tmpl = s.get("template", "")
fg, bg = self.get_seg_colors(s)
if stype == "block_connector":
connector_span = s.get("markup", "")
last_left.remove(s)
break
elif stype in ("text", "status") and any(c in tmpl for c in ("\u2570", "╰")):
col = fg or bg or "#FEF5ED"
clean_tmpl = re.sub(r"<[^>]+>", "", normalize_omp_template(tmpl)).strip()
symbol_match = re.search(r"([#$❯❮>➜➔➜λ▶»⮞])\s*$", clean_tmpl)
connector_text = clean_tmpl[:symbol_match.start()].strip() if symbol_match else clean_tmpl
connector_span = f"[{connector_text}](fg:{col})" if connector_text else ""
if symbol_match:
prompt_symbol = symbol_match.group(1).replace("$", "\\$")
line_character = {
"format": f"{connector_span}$symbol",
"success_symbol": f"{prompt_symbol} ",
"error_symbol": "[x ](bold #ef5350)",
}
last_left.remove(s)
break
# Check for pixelated badge cap + prompt character in last_left (e.g. cloud-context)
for i, s in enumerate(list(last_left)):
if s.get("type") == "root" and s.get("leading_diamond") in ("\ue0c7", "") and s.get("trailing_diamond") in ("\ue0c6", ""):
next_s = last_left[i + 1] if i + 1 < len(last_left) else None
if next_s and any(c in next_s.get("template", "") for c in (">", "❯", "➜", "\u276f")):
fg_badge, bg_badge = self.get_seg_colors(s)
b_col = bg_badge or "#dd0033"
t_col = fg_badge or "#151515"
char_fg = self.get_seg_colors(next_s)[0] or "#ffffff"
line_character = {
"format": "$symbol",
"success_symbol": f"[](fg:{b_col})[ ⚡ ](fg:{t_col} bg:{b_col})[](fg:{b_col})[ > ](bold {char_fg})",
"error_symbol": f"[](fg:{b_col})[ ⚡ ](fg:{t_col} bg:{b_col})[](fg:{b_col})[ > ](bold #ef5350)",
}
last_left.remove(s)
last_left.remove(next_s)
break
if has_bracket_frame and not line_character:
bracket_fg = getattr(self, "bracket_fg", "#CB4B16")
line_character = {
"format": "$symbol",
"success_symbol": f"[> ](fg:{bracket_fg})",
"error_symbol": f"[> ](fg:{bracket_fg})",
}
for s in reversed(last_left):
stype = s.get("type")
tmpl = s.get("template", "")
fg, bg = self.get_seg_colors(s)
lead = s.get("leading_diamond", "")
trail = s.get("trailing_diamond", "")
has_prompt_char = any(c in tmpl for c in ("\u276f", "\u276e", "❯", "❮", ">", "$", "#", "➜", "➔", "\u279c", "λ", "", "", "▶", "»", "\u2b9e", "⮞"))
is_ribbon_status = (stype == "status" and (bg or s.get("trailing_diamond") or s.get("powerline_symbol")) and not has_prompt_char)
if (stype == "text" or (stype == "status" and not is_ribbon_status)) or (stype == "session" and has_prompt_char):
clean_sym = normalize_omp_template(tmpl)
clean_sym = re.sub(r"<[^>]+>", "", clean_sym).strip()
if clean_sym == "\u279c":
clean_sym = "➔ "
if len(clean_sym) > 4 and not any(k in tmpl for k in ("{{ .UserName }}", ".UserName")):
continue
clean_sym = clean_sym.replace("\\", "").replace("$", "\\\\$")
clean_sym = clean_sym.replace("[", "\\[").replace("]", "\\]")
clean_sym = clean_sym.replace("(", "\\(").replace(")", "\\)")
sym = f"{clean_sym} " if clean_sym else "❯ "
col = fg or bg or "#22da6e"
err_col = "#ef5350"
for t in s.get("foreground_templates", []):
m = re.search(r"#([0-9a-fA-F]{3,6})", t)
if m:
err_col = f"#{m.group(1)}"
break
has_user = any(k in tmpl for k in ("{{ .UserName }}", ".UserName", "{{.UserName}}"))
is_pill_prompt = bg and ("\ue0b6" in lead or "\ue0b4" in trail or has_pill_diamonds)
if is_pill_prompt and has_user:
has_pill_prompt_user = True
self.modules["username"] = {
"style_user": f"fg:{fg or '#ffffff'} bg:{bg}",
"style_root": f"fg:#FFEB3B bg:{bg}",
"format": f"[](fg:{bg})[ $user ]($style)",
"show_always": True,
}
line_character = {
"format": "$symbol",
"success_symbol": f"[{sym}](bold {col} bg:{bg})[](fg:{bg}) ",
"error_symbol": f"[{sym}](bold {err_col} bg:{bg})[](fg:{bg}) ",
}
elif is_pill_prompt:
line_character = {
"format": "$symbol",
"success_symbol": f"[](fg:{bg})[ {sym}](bold {col} bg:{bg})[](fg:{bg}) ",
"error_symbol": f"[](fg:{bg})[ {sym}](bold {err_col} bg:{bg})[](fg:{bg}) ",
}
else:
self.char_is_plain = (s.get("style") == "plain")
line_character = {
"success_symbol": f"[{sym}](bold {col}) ",
"error_symbol": f"[{sym}](bold {err_col}) ",
}
if connector_span:
line_character["format"] = f"{connector_span}$symbol"
last_left.remove(s)
break
if not line_character:
if connector_span:
line_character = {
"format": f"{connector_span} $symbol",
"success_symbol": "",
"error_symbol": "[x ](bold #ef5350)",
}
else:
line_character = {
"success_symbol": "[❯ ](bold #22da6e) ",
"error_symbol": "[❯ ](bold #ef5350) ",
}
self.modules["character"] = line_character
# Step 4: Process Line 1
line1_left = prompt_lines[0]["left"]
line1_right = prompt_lines[0]["right"]
# Relocate metrics and runtimes from left to right on Line 1 ONLY if Line 1 has project identity and right side is initially empty
has_project_identity = any(s.get("type") in ("path", "git") for s in line1_left)
is_continuous_ribbon = (
has_rounded_powerline or is_flat_ribbon or has_pixel_powerline or
(theme_style == "powerline" and powerline_count > 0 and not has_pill_diamonds)
)
is_multiline_prompt = len(prompt_lines) > 1 and any(pl["left"] for pl in prompt_lines[1:])
has_dir_l1 = any(s.get("type") == "path" for s in line1_left)
if theme_style == "powerline" and has_dir_l1:
line1_left = [s for s in line1_left if s.get("type") != "time"]
prompt_lines[0]["left"] = [s for s in prompt_lines[0]["left"] if s.get("type") != "time"]
if (has_project_identity and has_dir_l1 and not has_block_diamonds and not line1_right and
not is_continuous_ribbon and
not has_bracket_frame and
not (is_multiline_prompt and len(prompt_lines) >= 3)):
relocated = []
remaining_l1 = []
for s in line1_left:
stype = s.get("type", "")
if stype in ("executiontime", "sysinfo", "memory", "battery", "time") or stype in ("nodejs", "python", "golang", "rust", "php", "ruby", "java", "dotnet", "package"):
relocated.append(s)
continue
remaining_l1.append(s)
prompt_lines[0]["left"] = remaining_l1
if relocated:
line1_right[:0] = relocated
# Check if runtimes should be injected
has_orig_runtimes = any(s.get("type") in RUNTIME_MAPPINGS for s in all_segs)
should_inject_runtimes = not has_block_diamonds and (
self.force_runtimes or (self.add_runtimes and has_orig_runtimes)
)
if (not line1_right and not self.force_runtimes) and (
is_continuous_ribbon or has_bracket_frame or not has_dir_l1 or not has_project_identity
):
should_inject_runtimes = False
# Parse Line 1 Left segments
parsed_l1_left = []
for s in prompt_lines[0]["left"]:
mod = self.parse_segment(s)
if mod:
if parsed_l1_left and parsed_l1_left[-1]["mod_name"] == mod["mod_name"]:
if parsed_l1_left[-1].get("leading") and not mod.get("leading"):
mod["leading"] = parsed_l1_left[-1]["leading"]
parsed_l1_left[-1] = mod
else:
parsed_l1_left.append(mod)
# Check if directory or git are missing completely across all lines
all_parsed_segs = [self.parse_segment(s) for pl in prompt_lines for s in pl["left"] + pl["right"]]
all_parsed_names = {p["mod_name"] for p in all_parsed_segs if p}
if "directory" not in all_parsed_names and not has_block_diamonds:
parsed_l1_left.insert(0, {
"mod_name": "directory", "var_name": "$directory",
"fg": "#82AAFF" if theme_style == "flat" else "#011627",
"bg": None if theme_style == "flat" else "#82AAFF",
"leading": "" if theme_style == "flat" else "╭─",
"trailing": "" if theme_style == "flat" else "",
"icon": " ", "raw_tmpl": "$path",
"options": {},
})
if "git_branch" not in all_parsed_names and not has_block_diamonds:
dir_idx = next((i for i, p in enumerate(parsed_l1_left) if p["mod_name"] == "directory"), -1)
target_idx = dir_idx + 1 if dir_idx >= 0 else len(parsed_l1_left)
parsed_l1_left.insert(target_idx, {
"mod_name": "git_branch", "var_name": "$git_branch",
"fg": "#addb67" if theme_style == "flat" else "#011627",
"bg": None if theme_style == "flat" else "#addb67",
"leading": "" if theme_style == "flat" else "",
"trailing": "" if theme_style == "flat" else "",
"icon": " ", "raw_tmpl": "$branch",
"options": {},
})
# Build Line 1 Left modules
self.parsed_l1_left = parsed_l1_left
line1_left_mods = []
for i, m in enumerate(parsed_l1_left):
prev_m = parsed_l1_left[i - 1] if i > 0 else None
next_m = parsed_l1_left[i + 1] if i + 1 < len(parsed_l1_left) else None
self.build_left_module(m, theme_style, next_mod=next_m, prev_mod=prev_m, is_first_on_line=(i == 0))
if m["var_name"] not in line1_left_mods:
line1_left_mods.append(m["var_name"])
if m["mod_name"] == "username" and m.get("has_host") and "$hostname" not in line1_left_mods:
line1_left_mods.append("$hostname")
if m["mod_name"] == "git_branch" and "$git_status" not in line1_left_mods:
line1_left_mods.append("$git_status")
# Parse Line 1 Right segments
parsed_l1_right = []
for s in line1_right:
mod = self.parse_segment(s)
if mod:
parsed_l1_right.append(mod)
# Deduplicate right-side modules by mod_name
seen_mods = set()
deduped_right = []
for p in parsed_l1_right:
if p["mod_name"] not in seen_mods:
seen_mods.add(p["mod_name"])
deduped_right.append(p)
parsed_l1_right = deduped_right
# Forward delimiters from leading of next module to trailing of current module
for i in range(len(parsed_l1_right) - 1):
curr_m = parsed_l1_right[i]
next_m = parsed_l1_right[i + 1]
if next_m.get("leading") in ("\u250b", "┆", "┋", "|", "│"):
curr_m["trailing"] = next_m["leading"]
next_m["leading"] = ""
# Inject developer runtimes if appropriate (and not already present on left)
has_left_runtime = any(p["mod_name"] in [r[0] for r in STANDARD_DEVELOPER_RUNTIMES] for p in parsed_l1_left)
if should_inject_runtimes and not has_left_runtime and not (is_single_line and theme_style == "powerline"):
has_runtime = any(p["mod_name"] in [r[0] for r in STANDARD_DEVELOPER_RUNTIMES] for p in parsed_l1_right)
if not has_runtime:
ins_idx = len(parsed_l1_right)
for i, p in enumerate(parsed_l1_right):
if p["mod_name"] in ("cmd_duration", "time"):
ins_idx = i
break
injected = []
for m_name, v_name, ic, fg in STANDARD_DEVELOPER_RUNTIMES:
if m_name not in seen_mods:
seen_mods.add(m_name)
injected.append({
"mod_name": m_name, "var_name": v_name,
"fg": fg, "bg": None if theme_style == "flat" else "#0b2942",
"leading": "", "trailing": "",
"icon": ic, "raw_tmpl": "$version",
"options": {},
})
parsed_l1_right[ins_idx:ins_idx] = injected
# Determine Right Style: flat, powerline (prev_bg), ribbon (unified), or pills
if theme_style == "flat":
right_style = "flat"
elif self.use_pills or has_pill_diamonds:
right_style = "pills"
elif theme_style == "powerline":
right_style = "powerline"
else:
right_style = "ribbon"
# Deduce ribbon background color for unified ribbon if applicable
ribbon_bg = self.ribbon_bg_override
if not ribbon_bg and right_style == "ribbon":
time_seg = next((p for p in parsed_l1_right if p["mod_name"] == "time"), None)
if time_seg and time_seg.get("bg"):
ribbon_bg = time_seg["bg"]
if not ribbon_bg:
user_seg = next((p for p in parsed_l1_right if p["mod_name"] == "username"), None)
if user_seg and user_seg.get("bg"):
ribbon_bg = user_seg["bg"]
if not ribbon_bg:
bgs = [p["bg"] for p in parsed_l1_right if p.get("bg")]
if bgs:
ribbon_bg = Counter(bgs).most_common(1)[0][0]
if not ribbon_bg:
for k in ("surface", "background", "mantle", "bg", "crust", "panel"):
if k in self.palette:
ribbon_bg = self.resolve_color(f"p:{k}")
if ribbon_bg:
break
if not ribbon_bg:
ribbon_bg = "#0b2942"
line1_right_mods = []
for m in parsed_l1_right:
self.build_right_module(m, right_style, ribbon_bg)
if m["var_name"] not in line1_right_mods:
line1_right_mods.append(m["var_name"])
if m["mod_name"] == "username" and m.get("has_host") and "$hostname" not in line1_right_mods:
line1_right_mods.append("$hostname")
if m["mod_name"] == "git_branch" and "$git_status" not in line1_right_mods:
line1_right_mods.append("$git_status")
# Step 5: Process Subsequent Lines (Line 2+)
subsequent_line_mods: List[List[str]] = []
for pl in prompt_lines[1:]:
curr_sub_mods = []
parsed_pl_left = []
for s in pl["left"]:
mod = self.parse_segment(s)
if mod:
if parsed_pl_left and parsed_pl_left[-1]["mod_name"] == mod["mod_name"]:
if parsed_pl_left[-1].get("leading") and not mod.get("leading"):
mod["leading"] = parsed_pl_left[-1]["leading"]
parsed_pl_left[-1] = mod
else:
parsed_pl_left.append(mod)
for i, mod in enumerate(parsed_pl_left):
prev_m = parsed_pl_left[i - 1] if i > 0 else None
next_m = parsed_pl_left[i + 1] if i + 1 < len(parsed_pl_left) else None
if mod.get("mod_name") != "connector":
self.build_left_module(mod, theme_style, next_mod=next_m, prev_mod=prev_m, is_first_on_line=(i == 0))
if mod["var_name"] not in curr_sub_mods:
curr_sub_mods.append(mod["var_name"])
if mod["mod_name"] == "username" and mod.get("has_host") and "$hostname" not in curr_sub_mods:
curr_sub_mods.append("$hostname")
if mod["mod_name"] == "git_branch" and "$git_status" not in curr_sub_mods:
curr_sub_mods.append("$git_status")
has_actual_modules = any(m.startswith("$") for m in curr_sub_mods)
if curr_sub_mods and has_actual_modules:
subsequent_line_mods.append(curr_sub_mods)
has_rprompt = any(b.get("type") == "rprompt" for b in blocks)
# Attach $character (and $username if pill prompt user) to the last line
if is_single_line:
if has_rprompt or theme_style == "powerline":
if has_pill_prompt_user and "$username" not in line1_left_mods:
line1_left_mods.append("$username")
if "$character" not in line1_left_mods:
line1_left_mods.append("$character")
else:
if has_pill_prompt_user and "$username" not in line1_right_mods and "$username" not in line1_left_mods:
line1_right_mods.append("$username")
if "$character" not in line1_right_mods:
line1_right_mods.append("$character")
else:
if not subsequent_line_mods or len(subsequent_line_mods) < (len(prompt_lines) - 1):
subsequent_line_mods.append([])
if has_pill_prompt_user and "$username" not in subsequent_line_mods[-1]:
subsequent_line_mods[-1].append("$username")
subsequent_line_mods[-1].append("$character")
# Configure character module for single-line powerline
if is_single_line and theme_style == "powerline":
last_left_mod = parsed_l1_left[-1] if parsed_l1_left else None
last_has_closed = bool(
last_left_mod and (
last_left_mod.get("trailing_diamond") or
"<transparent" in last_left_mod.get("trailing", "")
)
)
dir_mod = next((p for p in parsed_l1_left if p["mod_name"] == "directory"), None)
git_mod = next((p for p in parsed_l1_left if p["mod_name"] == "git_branch"), None)
is_same_bg_powerline = bool(dir_mod and git_mod and dir_mod.get("bg") == git_mod.get("bg"))
if is_same_bg_powerline or last_has_closed:
self.modules["character"] = {
"format": "$symbol",
"success_symbol": "",
"error_symbol": "",
}
else:
pwr_sym = getattr(self, "powerline_symbol", "\ue0b0")
close_glyph = "\ue0b4" if (pwr_sym in ("\ue0b4", "") or getattr(self, "powerline_symbol", "") in ("\ue0b4", "")) else ("\ue0c4" if pwr_sym == "\ue0c4" else "\ue0b0")
self.modules["character"] = {
"format": "$symbol",
"success_symbol": f"[{close_glyph}](fg:prev_bg) ",
"error_symbol": f"[{close_glyph}](fg:prev_bg) ",
}
elif not is_single_line and theme_style == "powerline":
last_line_segs = prompt_lines[-1]["left"] if prompt_lines else []
last_seg = last_line_segs[-1] if last_line_segs else None
char_is_plain = getattr(self, "char_is_plain", False)
if last_seg and (last_seg.get("background") or last_seg.get("trailing_diamond") == "\ue0b0") and not char_is_plain:
sym_fmt = self.modules.get("character", {}).get("format", "$symbol")
if "" not in sym_fmt:
if "character" not in self.modules:
self.modules["character"] = {}
self.modules["character"]["format"] = f"[](fg:prev_bg) {sym_fmt}"
return self.render_toml(
line1_left_mods=line1_left_mods,
line1_right_mods=line1_right_mods,
subsequent_lines=subsequent_line_mods,
is_single_line=is_single_line,
right_style=right_style,
ribbon_bg=ribbon_bg,
has_rprompt=has_rprompt,
)
def parse_segment(self, s: Dict[str, Any]) -> Optional[Dict[str, Any]]:
res = self._parse_segment_raw(s)
if res:
res["trailing_diamond"] = s.get("trailing_diamond", "")
res["leading_diamond"] = s.get("leading_diamond", "")
res["seg_style"] = s.get("style", "")
tmpl = s.get("template", "")
m_frame = re.search(r"<([#a-zA-Z0-9_\-]+)>([┏┖┗\u250f\u2514\u2516])?\[</>", tmpl)
bracket_color = None
box_char = ""
if m_frame:
bracket_color = self.resolve_color(m_frame.group(1))
box_char = m_frame.group(2) or ""
elif any(c in tmpl for c in ("┏", "\u250f", "┗", "┖", "\u2514", "\u2516")):
for c in ("┏", "\u250f", "┗", "┖", "\u2514", "\u2516"):
if c in tmpl:
box_char = c
break
m_col = re.search(r"<([#a-zA-Z0-9_\-]+)>", tmpl)
if m_col:
bracket_color = self.resolve_color(m_col.group(1))
if bracket_color or box_char:
res["bracket_fg"] = bracket_color
res["box_char"] = box_char
res["is_bracketed"] = True
return res
def _parse_segment_raw(self, s: Dict[str, Any]) -> Optional[Dict[str, Any]]:
stype = s.get("type", "")
if stype == "block_connector":
return {
"mod_name": "connector", "var_name": s.get("markup", ""),
"fg": None, "bg": None,
"leading": "", "trailing": "",
"icon": "", "raw_tmpl": "",
"options": {},
"template": "",
"is_bracketed": False,
}
fg, bg = self.get_seg_colors(s)
tmpl = s.get("template", "")
options = s.get("options") or s.get("properties") or {}
lead = s.get("leading_diamond", "")
trail = s.get("trailing_diamond", "") or s.get("powerline_symbol", "")
if not lead and "<transparent" in tmpl:
m_lead = re.search(r"<transparent[^>]*>([\ue0b0\ue0b2])</>", tmpl)
if m_lead:
lead = m_lead.group(0)
is_bracketed = (tmpl.strip().startswith("[") and tmpl.strip().endswith("]")) or "<#CB4B16>[" in tmpl
extra_text = ""
if stype == "session":
m = re.search(r"\{\{\s*\.UserName\s*\}\}(.*?)\{\{\s*\.HostName\s*\}\}", tmpl)
if m:
extra_text = normalize_omp_template(m.group(1))
elif ".HostName" in tmpl:
extra_text = "@"
elif stype == "executiontime":
if "\ue601" in tmpl:
options["icon"] = " "
elif "\ueba2" in tmpl:
options["icon"] = " "
if stype == "os":
win_sym = options.get("windows") or ""
return {
"mod_name": "os", "var_name": "$os",
"fg": fg or "#011627", "bg": bg,
"leading": lead, "trailing": trail,
"icon": win_sym, "raw_tmpl": "$symbol",
"options": options,