-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatusline.c
More file actions
1840 lines (1703 loc) · 53.2 KB
/
Copy pathstatusline.c
File metadata and controls
1840 lines (1703 loc) · 53.2 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
// statusline - Fast status line generator for bash and Claude Code
// Usage: statusline [--bash|--claude] [--ps1] [--exit-code=N] [--jobs=N]
#define _GNU_SOURCE
#ifndef VERSION
#define VERSION "unknown"
#endif
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pwd.h>
#include <spawn.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#define JSMN_STATIC
#define JSMN_PARENT_LINKS
#include "jsmn.h"
#define BUF_SIZE 65536
#define PATH_MAX_LEN 4096
// Claude payload counts ~125 jsmn tokens with every field present; 512 leaves
// headroom for added_dirs[] and future fields. Subagent tasks[] is far larger.
#define MAX_TOKENS 512
#define MAX_TOKENS_SUB 4096
#define MAX_TOKENS_ANTIGRAVITY 4096
#define GIT_REF_PREFIX "ref: refs/heads/"
#define GIT_REF_PREFIX_LEN 16
enum { MODE_CLAUDE, MODE_BASH, MODE_SUBAGENT, MODE_ANTIGRAVITY };
enum { FMT_RAW, FMT_PS1 };
static char g_input[BUF_SIZE];
static int g_mode = MODE_CLAUDE;
static int g_fmt = FMT_RAW;
static int g_no_color = 0;
static int g_exit_code = 0;
static int g_jobs = 0;
static int g_shlvl = 0;
// Colors
#define RST "\033[0m"
#define DIM "\033[2m"
#define RED "\033[0;31m"
#define BLD_RED "\033[1;31m"
#define RED_F "\033[31m"
#define GRN_F "\033[32m"
#define YEL_F "\033[33m"
#define YEL "\033[0;33m"
#define BLD_YEL "\033[1;33m"
#define GRN "\033[1;32m"
#define DIM_GRN "\033[0;32m"
#define CYN_F "\033[36m"
#define CYN "\033[0;36m"
#define BLD_CYN "\033[1;36m"
#define BRIGHT_BLU "\033[94m"
#define BRIGHT_CYN "\033[96m"
#define WHT_F "\033[37m"
#define WHT "\033[0;37m"
#define BLD_WHT "\033[1;37m"
static void color(const char *c) {
if (g_no_color)
return;
if (g_fmt == FMT_PS1)
printf("\001%s\002", c);
else
printf("%s", c);
}
static int pathcat(char *out, size_t sz, const char *a, const char *b) {
int n = snprintf(out, sz, "%s/%s", a, b);
return n >= 0 && (size_t)n < sz;
}
// ==================== JSON path helpers (over jsmn) ====================
// Find a token by dot-separated path, starting from object token `root`
// (e.g. "model.display_name"). Returns the value-token index, or -1 if any
// segment is missing.
static int jp_find_from(const char *buf, jsmntok_t *t, int n, int root,
const char *path) {
if (n <= 0 || root < 0 || root >= n)
return -1;
int cur = root;
const char *p = path;
while (*p) {
const char *seg = p;
while (*p && *p != '.')
p++;
size_t seglen = (size_t)(p - seg);
if (t[cur].type != JSMN_OBJECT)
return -1;
int found = -1;
for (int i = cur + 1; i < n; i++) {
if (t[i].parent == cur && t[i].type == JSMN_STRING) {
size_t klen = (size_t)(t[i].end - t[i].start);
if (klen == seglen && strncmp(buf + t[i].start, seg, seglen) == 0) {
found = i + 1;
break;
}
}
}
if (found < 0)
return -1;
cur = found;
if (*p == '.')
p++;
}
return cur;
}
static int jp_find(const char *buf, jsmntok_t *t, int n, const char *path) {
return jp_find_from(buf, t, n, 0, path);
}
static int jp_is_null(const char *buf, jsmntok_t *tok) {
return tok->type == JSMN_PRIMITIVE && (tok->end - tok->start) == 4 &&
strncmp(buf + tok->start, "null", 4) == 0;
}
static int jp_str_from(const char *buf, jsmntok_t *t, int n, int root,
const char *path, char *out, size_t sz) {
int i = jp_find_from(buf, t, n, root, path);
if (i < 0 || t[i].type != JSMN_STRING)
return 0;
size_t len = (size_t)(t[i].end - t[i].start);
if (len >= sz)
len = sz - 1;
memcpy(out, buf + t[i].start, len);
out[len] = '\0';
return 1;
}
static int jp_str(const char *buf, jsmntok_t *t, int n, const char *path,
char *out, size_t sz) {
return jp_str_from(buf, t, n, 0, path, out, sz);
}
static long jp_long_from(const char *buf, jsmntok_t *t, int n, int root,
const char *path, long dflt) {
int i = jp_find_from(buf, t, n, root, path);
if (i < 0 || t[i].type != JSMN_PRIMITIVE || jp_is_null(buf, &t[i]))
return dflt;
char *endp;
errno = 0;
long v = strtol(buf + t[i].start, &endp, 10);
if (endp == buf + t[i].start || errno == ERANGE)
return dflt;
return v;
}
static long jp_long(const char *buf, jsmntok_t *t, int n, const char *path,
long dflt) {
return jp_long_from(buf, t, n, 0, path, dflt);
}
// 1 = true, 0 = false, dflt if missing/null/not a boolean primitive.
static int jp_bool(const char *buf, jsmntok_t *t, int n, const char *path,
int dflt) {
int i = jp_find(buf, t, n, path);
if (i < 0 || t[i].type != JSMN_PRIMITIVE || jp_is_null(buf, &t[i]))
return dflt;
char c = buf[t[i].start];
if (c == 't')
return 1;
if (c == 'f')
return 0;
return dflt;
}
// Resolve a dot-path to an array token; return its index or -1.
static int jp_find_array(const char *buf, jsmntok_t *t, int n,
const char *path) {
int i = jp_find(buf, t, n, path);
if (i < 0 || t[i].type != JSMN_ARRAY)
return -1;
return i;
}
// Return the token index of the next direct child of array token `arr` at or
// after `from`, or -1 when exhausted. jsmn sets each element's parent to the
// array token (nested objects/arrays point at their own container), so the
// parent==arr test selects only top-level elements. Pass the previous result
// plus its subtree (i.e. prev+1) as `from` to walk all elements in order.
static int jp_array_next(jsmntok_t *t, int n, int arr, int from) {
for (int i = from; i < n; i++)
if (t[i].parent == arr)
return i;
return -1;
}
static double jp_dbl(const char *buf, jsmntok_t *t, int n, const char *path,
double dflt) {
int i = jp_find(buf, t, n, path);
if (i < 0 || t[i].type != JSMN_PRIMITIVE || jp_is_null(buf, &t[i]))
return dflt;
char *endp;
errno = 0;
double v = strtod(buf + t[i].start, &endp);
if (endp == buf + t[i].start || errno == ERANGE)
return dflt;
return v;
}
// ==================== stdin ====================
static void read_stdin(void) {
if (g_mode == MODE_BASH || isatty(STDIN_FILENO))
return;
size_t n, total = 0;
while ((n = fread(g_input + total, 1, sizeof(g_input) - total - 1, stdin)) >
0) {
total += n;
if (total >= sizeof(g_input) - 1)
break;
}
if (ferror(stdin))
total = 0;
g_input[total] = '\0';
}
// ==================== bash-mode env blocks ====================
static void pr_venv(void) {
if (g_mode != MODE_BASH)
return;
const char *v = getenv("VIRTUAL_ENV");
if (!v || !*v)
return;
const char *n = strrchr(v, '/');
color(BLD_WHT);
printf("[%s]", n ? n + 1 : v);
color(RST);
printf(" ");
}
static void pr_ssh(void) {
if (g_mode != MODE_BASH)
return;
if (!getenv("SSH_TTY"))
return;
color(YEL);
printf("-ssh-");
color(RST);
printf(" ");
}
static void pr_shlvl(void) {
if (g_mode != MODE_BASH || g_shlvl <= 1)
return;
color(BLD_CYN);
printf("(%d)", g_shlvl);
color(RST);
printf(" ");
}
// ==================== git ====================
// start==NULL uses getcwd; otherwise searches starting from `start`.
static int find_git(const char *start, char *gitdir, char *worktree,
size_t sz) {
char cwd[PATH_MAX_LEN];
if (start) {
snprintf(cwd, sizeof(cwd), "%s", start);
} else if (!getcwd(cwd, sizeof(cwd))) {
return 0;
}
while (*cwd) {
char dotgit[PATH_MAX_LEN];
if (!pathcat(dotgit, sizeof(dotgit), cwd, ".git"))
return 0;
struct stat st;
if (stat(dotgit, &st) == 0) {
if (S_ISDIR(st.st_mode)) {
snprintf(gitdir, sz, "%s", dotgit);
snprintf(worktree, sz, "%s", cwd);
return 1;
}
if (S_ISREG(st.st_mode)) {
FILE *f = fopen(dotgit, "r");
if (!f)
return 0;
char line[PATH_MAX_LEN];
if (!fgets(line, sizeof(line), f)) {
fclose(f);
return 0;
}
fclose(f);
line[strcspn(line, "\n\r")] = '\0';
if (strncmp(line, "gitdir: ", 8) != 0)
return 0;
const char *gd = line + 8;
if (gd[0] == '/')
snprintf(gitdir, sz, "%s", gd);
else
pathcat(gitdir, sz, cwd, gd);
snprintf(worktree, sz, "%s", cwd);
return 1;
}
}
char *p = strrchr(cwd, '/');
if (!p || p == cwd)
break;
*p = '\0';
}
return 0;
}
// Fills br with branch name or short SHA; returns 1 on success.
static int git_branch_name(const char *gitdir, char *br, size_t sz) {
char hp[PATH_MAX_LEN];
if (!pathcat(hp, sizeof(hp), gitdir, "HEAD"))
return 0;
FILE *f = fopen(hp, "r");
if (!f)
return 0;
char head[256];
if (!fgets(head, sizeof(head), f)) {
fclose(f);
return 0;
}
fclose(f);
head[strcspn(head, "\n")] = '\0';
if (strncmp(head, GIT_REF_PREFIX, GIT_REF_PREFIX_LEN) == 0)
snprintf(br, sz, "%s", head + GIT_REF_PREFIX_LEN);
else
snprintf(br, sz, "%.7s", head);
return 1;
}
extern char **environ;
// Exit 0 = clean, 1 = dirty, anything else = treat as clean.
static int git_dirty(const char *gitdir, const char *worktree) {
char path[PATH_MAX_LEN];
const char *ops[] = {"MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD",
"REBASE_HEAD", "BISECT_LOG"};
for (size_t i = 0; i < sizeof(ops) / sizeof(ops[0]); i++) {
if (pathcat(path, sizeof(path), gitdir, ops[i]) && access(path, F_OK) == 0)
return 1;
}
posix_spawn_file_actions_t fa;
if (posix_spawn_file_actions_init(&fa) != 0)
return 0;
if (posix_spawn_file_actions_addopen(&fa, 0, "/dev/null", O_RDONLY, 0) != 0 ||
posix_spawn_file_actions_addopen(&fa, 1, "/dev/null", O_WRONLY, 0) != 0 ||
posix_spawn_file_actions_addopen(&fa, 2, "/dev/null", O_WRONLY, 0) != 0) {
posix_spawn_file_actions_destroy(&fa);
return 0;
}
char *argv[] = {"git", "-C", (char *)worktree,
"diff-index", "--quiet", "HEAD",
"--", NULL};
pid_t pid;
int rc = posix_spawnp(&pid, "git", &fa, NULL, argv, environ);
posix_spawn_file_actions_destroy(&fa);
if (rc != 0)
return 0;
int status = 0;
while (waitpid(pid, &status, 0) < 0) {
if (errno != EINTR)
return 0;
}
if (!WIFEXITED(status))
return 0;
return WEXITSTATUS(status) == 1;
}
static int git_has_stash(const char *gitdir) {
char path[PATH_MAX_LEN];
return pathcat(path, sizeof(path), gitdir, "refs/stash") &&
access(path, F_OK) == 0;
}
// Bash-mode git block: (branch) [*] [$]
static void pr_git(void) {
char gd[PATH_MAX_LEN], wt[PATH_MAX_LEN];
if (!find_git(NULL, gd, wt, sizeof(gd)))
return;
char br[256];
if (!git_branch_name(gd, br, sizeof(br)))
return;
color(RED);
printf("(%s)", br);
color(RST);
if (git_dirty(gd, wt)) {
color(BLD_RED);
printf(" *");
color(RST);
}
if (git_has_stash(gd)) {
color(YEL);
printf(" $");
color(RST);
}
printf(" ");
}
// ==================== k8s ====================
// Minimal YAML parser for kubeconfig; assumes standard kubectl formatting.
static void pr_k8s(void) {
char kc[PATH_MAX_LEN];
const char *e = getenv("KUBECONFIG");
if (e && *e) {
snprintf(kc, sizeof(kc), "%s", e);
char *p = strchr(kc, ':');
if (p)
*p = '\0';
} else {
const char *h = getenv("HOME");
if (!h)
return;
snprintf(kc, sizeof(kc), "%s/.kube/config", h);
}
FILE *f = fopen(kc, "r");
if (!f)
return;
char line[1024], ctx[1024] = "", ns[256] = "";
int in_ctx = 0, found = 0;
while (fgets(line, sizeof(line), f)) {
if (!*ctx && strncmp(line, "current-context:", 16) == 0) {
char *v = line + 16;
while (*v == ' ')
v++;
snprintf(ctx, sizeof(ctx), "%s", v);
ctx[strcspn(ctx, "\n\r")] = '\0';
rewind(f);
} else if (*ctx) {
if (strncmp(line, "contexts:", 9) == 0) {
found = 1;
continue;
}
if (!found)
continue;
if (line[0] != ' ' && line[0] != '-' && line[0] != '\n')
break;
char *np = strstr(line, "name:");
if (np) {
char *v = np + 5;
while (*v == ' ')
v++;
char nm[256];
snprintf(nm, sizeof(nm), "%s", v);
nm[strcspn(nm, "\n\r")] = '\0';
in_ctx = strcmp(nm, ctx) == 0;
}
if (in_ctx && (np = strstr(line, "namespace:"))) {
char *v = np + 10;
while (*v == ' ')
v++;
snprintf(ns, sizeof(ns), "%s", v);
ns[strcspn(ns, "\n\r")] = '\0';
break;
}
}
}
fclose(f);
if (!*ctx)
return;
color(GRN);
printf("%s", ctx);
if (*ns) {
color(WHT);
printf("|");
color(DIM_GRN);
printf("%s", ns);
}
color(RST);
printf(" ");
}
// ==================== common (bash-mode) ====================
static void pr_userhost(void) {
char hn[256] = "unknown";
if (gethostname(hn, sizeof(hn)) != 0)
hn[0] = '?', hn[1] = '\0';
hn[sizeof(hn) - 1] = '\0';
char *p = strchr(hn, '.');
if (p)
*p = '\0';
struct passwd *pw = getpwuid(getuid());
color(CYN);
printf("%s", pw ? pw->pw_name : "?");
color(BLD_CYN);
printf("@%s", hn);
color(RST);
}
// Interior parent dirs above which the bash cwd slug is abbreviated to
// initials. "Interior" excludes the root marker (~ or /) and the current
// dir, which is always shown in full.
#define PATH_TRUNC_INTERIOR 3
// Index just past the first UTF-8 codepoint of seg[i..len), so a multibyte
// name is never split mid-character.
static size_t cwd_cp_next(const char *seg, size_t i, size_t len) {
if (i >= len)
return i;
unsigned char c = (unsigned char)seg[i++];
if (c >= 0xC2) {
int extra = (c >= 0xF0) ? 3 : (c >= 0xE0) ? 2 : 1;
while (extra-- > 0 && i < len && ((unsigned char)seg[i] & 0xC0) == 0x80)
i++;
}
return i;
}
// Bytes to keep when abbreviating an interior component: the first codepoint,
// plus a second only for a hidden ".name" dir so it reads as ".x" not a bare
// ".". Literal "." / ".." are kept whole; a "..name" dir keeps only its first
// '.' so it never renders as a misleading "..".
static size_t cwd_keep(const char *seg, size_t len) {
if (len == 0)
return 0;
if (seg[0] == '.') {
if (len <= 2)
return len;
if (seg[1] == '.')
return cwd_cp_next(seg, 0, len);
return cwd_cp_next(seg, cwd_cp_next(seg, 0, len), len);
}
return cwd_cp_next(seg, 0, len);
}
static void pr_cwd(void) {
char cwd[PATH_MAX_LEN];
if (!getcwd(cwd, sizeof(cwd)))
return;
color(BLD_YEL);
const char *h = getenv("HOME");
size_t hl = h ? strlen(h) : 0;
// Only abbreviate HOME when it's a full-path-component prefix of cwd,
// so HOME=/Users/weldon doesn't match cwd=/Users/weldon2.
char root = '\0';
const char *rem = cwd;
if (h && hl > 0 && strncmp(cwd, h, hl) == 0 &&
(cwd[hl] == '\0' || cwd[hl] == '/')) {
root = '~';
rem = cwd + hl;
}
// Count '/'-delimited components in the remainder; "interior" excludes the
// current (last) dir.
int nseg = 0;
for (const char *p = rem; *p;) {
if (*p == '/') {
p++;
continue;
}
while (*p && *p != '/')
p++;
nseg++;
}
int interior = nseg > 0 ? nseg - 1 : 0;
if (interior <= PATH_TRUNC_INTERIOR) {
// Shallow path: byte-for-byte identical to the pre-truncation output.
if (root == '~')
printf("~%s", cwd + hl);
else
printf("%s", cwd);
} else {
// Abbreviate every interior dir to its initial codepoint(s); keep the
// current dir in full. A '/' precedes each component (the home case is
// prefixed with '~'); the leading '/' of an absolute path is supplied by
// the first component's separator, so no "//" appears.
if (root == '~')
putchar('~');
int i = 0;
for (const char *p = rem; *p;) {
if (*p == '/') {
p++;
continue;
}
const char *s = p;
while (*p && *p != '/')
p++;
size_t seglen = (size_t)(p - s);
putchar('/');
size_t keep = (i == nseg - 1) ? seglen : cwd_keep(s, seglen);
fwrite(s, 1, keep, stdout);
i++;
}
}
color(RST);
}
static void pr_time(void) {
time_t now = time(NULL);
struct tm *t = localtime(&now);
if (!t) {
color(WHT);
printf("--:--:--");
color(RST);
return;
}
color(WHT);
printf("%02d:%02d:%02d", t->tm_hour, t->tm_min, t->tm_sec);
color(RST);
}
static void pr_prompt(void) {
if (g_mode != MODE_BASH)
return;
pr_time();
printf(" ");
if (g_exit_code) {
color(BLD_RED);
printf("%d ", g_exit_code);
}
color(geteuid() == 0 ? BLD_RED : RST);
printf("%c", geteuid() == 0 ? '#' : '$');
color(RST);
printf(" ");
}
// ==================== Claude mode ====================
// Strip leading "Claude " or "Gemini " prefix if present; else return input.
static const char *short_model(const char *full) {
if (strncmp(full, "Claude ", 7) == 0)
return full + 7;
if (strncmp(full, "Gemini ", 7) == 0)
return full + 7;
return full;
}
// "1h2m" / "2m3s" / "5s". Empty string for ms <= 0.
static void fmt_duration_ms(char *out, size_t sz, long ms) {
if (ms <= 0) {
out[0] = '\0';
return;
}
long total_sec = ms / 1000;
long hours = total_sec / 3600;
long minutes = (total_sec % 3600) / 60;
long seconds = total_sec % 60;
if (hours > 0)
snprintf(out, sz, "%ldh%ldm", hours, minutes);
else if (minutes > 0)
snprintf(out, sz, "%ldm%lds", minutes, seconds);
else
snprintf(out, sz, "%lds", seconds);
}
// Compact token count: "999", "12k", "1.2M".
static void fmt_tokens(char *out, size_t sz, long n) {
if (n < 0)
n = 0;
if (n < 1000)
snprintf(out, sz, "%ld", n);
else if (n < 1000000)
snprintf(out, sz, "%ldk", n / 1000);
else
snprintf(out, sz, "%.1fM", n / 1000000.0);
}
static const char *path_basename(const char *p) {
static char buf[PATH_MAX_LEN];
size_t len = strlen(p);
while (len > 1 && p[len - 1] == '/')
len--;
const char *s = p;
for (size_t i = 0; i < len; i++)
if (p[i] == '/')
s = p + i + 1;
size_t blen = (p + len) - s;
if (blen >= sizeof(buf))
blen = sizeof(buf) - 1;
memcpy(buf, s, blen);
buf[blen] = '\0';
return buf;
}
// ==================== segments (width-aware emission) ====================
// Claude-mode lines are built as segments first, then emitted: when COLUMNS is
// set, low-priority segments are dropped to fit. `vis` tracks display width
// (escapes contribute 0); `sep` is the join style to the previous kept segment.
enum { SEP_NONE, SEP_SPACE, SEP_PIPE };
#define SEG_BUF 512
typedef struct {
char text[SEG_BUF];
size_t len;
int vis; // display columns, excluding escape sequences
int prio; // lower kept first; 0 is never dropped
int sep; // SEP_* join to the previous kept segment
int used;
} seg_t;
// Append literal bytes (no display-width change): colors, escapes, glyphs.
static void seg_raw(seg_t *s, const char *str) {
while (*str && s->len < sizeof(s->text) - 1)
s->text[s->len++] = *str++;
s->text[s->len] = '\0';
}
// Append a color code, mirroring color() (respects NO_COLOR / PS1 wrapping).
static void seg_color(seg_t *s, const char *c) {
if (g_no_color)
return;
if (g_fmt == FMT_PS1) {
seg_raw(s, "\001");
seg_raw(s, c);
seg_raw(s, "\002");
} else {
seg_raw(s, c);
}
}
// Append formatted plain text; display width = its codepoint count. Always
// call as seg_addf(s, "%s", userdata): a user string used as the format would
// be a format-string bug (caught by -Wformat-security via the attribute).
static void seg_addf(seg_t *s, const char *fmt, ...)
__attribute__((format(printf, 2, 3)));
static void seg_addf(seg_t *s, const char *fmt, ...) {
char tmp[SEG_BUF];
va_list ap;
va_start(ap, fmt);
int w = vsnprintf(tmp, sizeof(tmp), fmt, ap);
va_end(ap);
if (w < 0)
return;
// Count display width only on the bytes seg_raw actually appended (it stops
// at SEG_BUF), so a near-full segment doesn't overstate its width. Codepoints
// (non-continuation bytes) approximate columns; wide chars (emoji, CJK) in
// data strings undercount by one per glyph, which only softens truncation.
size_t before = s->len;
seg_raw(s, tmp);
for (size_t i = before; i < s->len; i++)
if (((unsigned char)s->text[i] & 0xC0) != 0x80)
s->vis++;
}
// Append a UTF-8 glyph with an explicit display width (2 for emoji, 1 for
// arrows) since terminal width can't be derived from the bytes.
static void seg_addglyph(seg_t *s, const char *utf8, int cols) {
seg_raw(s, utf8);
s->vis += cols;
}
// 12-char progress bar (buffered twin of pr_progress_bar).
static void seg_progress_bar(seg_t *s, int pct) {
if (pct < 0)
pct = 0;
if (pct > 100)
pct = 100;
const int width = 12;
int filled = pct * width / 100;
const char *fc = (pct < 50) ? GRN_F : (pct < 80) ? YEL_F : RED_F;
seg_color(s, fc);
for (int i = 0; i < filled; i++)
seg_raw(s, "\xE2\x96\x88"); // U+2588 FULL BLOCK
seg_color(s, DIM);
for (int i = 0; i < width - filled; i++)
seg_raw(s, "\xE2\xA3\xBF"); // U+28FF BRAILLE PATTERN DOTS-12345678
seg_color(s, RST);
s->vis += width;
}
// 1 if the terminal likely supports OSC 8 hyperlinks (cached).
static int hyperlinks_ok(void) {
static int cached = -1;
if (cached >= 0)
return cached;
cached = 0;
if (g_no_color || g_fmt == FMT_PS1)
return cached;
const char *force = getenv("FORCE_HYPERLINK");
if (force && *force) {
cached = 1;
return cached;
}
if (getenv("VTE_VERSION")) {
cached = 1;
return cached;
}
const char *tp = getenv("TERM_PROGRAM");
if (tp && (strcmp(tp, "iTerm.app") == 0 || strcmp(tp, "WezTerm") == 0 ||
strcmp(tp, "vscode") == 0 || strcmp(tp, "ghostty") == 0))
cached = 1;
return cached;
}
// Append `text` as an OSC 8 hyperlink to `url` when supported, else plain text.
// Display width counts only the visible `text`.
static void seg_link(seg_t *s, const char *url, const char *text) {
// Only emit the link form if the open + url + text + close all fit; otherwise
// a truncated sequence would leave the terminal in active-hyperlink mode.
size_t need = 5 + strlen(url) + 1 + strlen(text) + 7;
if (hyperlinks_ok() && s->len + need < sizeof(s->text)) {
seg_raw(s, "\033]8;;");
seg_raw(s, url);
seg_raw(s, "\a");
seg_addf(s, "%s", text);
seg_raw(s, "\033]8;;\a");
} else {
seg_addf(s, "%s", text);
}
}
static int sep_cols(int sep) {
return sep == SEP_PIPE ? 3 : sep == SEP_SPACE ? 1 : 0;
}
// Total display width of the kept segments in display order, including the
// separators between consecutive kept segments (the first kept gets none).
static int line_width(seg_t *segs, int count) {
int w = 0, first = 1;
for (int i = 0; i < count; i++) {
if (!segs[i].used)
continue;
if (!first)
w += sep_cols(segs[i].sep);
w += segs[i].vis;
first = 0;
}
return w;
}
static size_t buf_app(char *out, size_t sz, size_t pos, const char *str) {
while (*str && pos < sz - 1)
out[pos++] = *str++;
out[pos] = '\0';
return pos;
}
// Append a color code into a buffer, mirroring color().
static size_t buf_color(char *out, size_t sz, size_t pos, const char *c) {
if (g_no_color)
return pos;
if (g_fmt == FMT_PS1) {
pos = buf_app(out, sz, pos, "\001");
pos = buf_app(out, sz, pos, c);
pos = buf_app(out, sz, pos, "\002");
} else {
pos = buf_app(out, sz, pos, c);
}
return pos;
}
// Decide which segments fit `budget` columns (0 = unlimited), then render them
// in display order into `out`. prio 0 is always kept; higher prios are added
// cheapest-first while the line fits. The first kept segment emits no
// separator, matching the original "first shown" behavior.
static void seg_render(seg_t *segs, int count, int budget, char *out,
size_t sz) {
if (budget <= 0) {
for (int i = 0; i < count; i++)
segs[i].used = 1;
} else {
int maxprio = 0;
for (int i = 0; i < count; i++) {
segs[i].used = (segs[i].prio == 0);
if (segs[i].prio > maxprio)
maxprio = segs[i].prio;
}
for (int pr = 1; pr <= maxprio; pr++) {
for (int i = 0; i < count; i++) {
if (segs[i].used || segs[i].prio != pr)
continue;
segs[i].used = 1;
if (line_width(segs, count) > budget)
segs[i].used = 0;
}
}
}
size_t pos = 0;
out[0] = '\0';
int first = 1;
for (int i = 0; i < count; i++) {
if (!segs[i].used)
continue;
if (!first) {
if (segs[i].sep == SEP_PIPE) {
pos = buf_app(out, sz, pos, " ");
pos = buf_color(out, sz, pos, DIM);
pos = buf_app(out, sz, pos, "|");
pos = buf_color(out, sz, pos, RST);
pos = buf_app(out, sz, pos, " ");
} else if (segs[i].sep == SEP_SPACE) {
pos = buf_app(out, sz, pos, " ");
}
}
pos = buf_app(out, sz, pos, segs[i].text);
first = 0;
}
}
static void seg_emit_line(seg_t *segs, int count, int budget) {
char line[8192];
seg_render(segs, count, budget, line, sizeof(line));
fputs(line, stdout);
}
// COLUMNS budget for width-aware truncation; <=0 means unlimited.
static int term_columns(void) {
struct winsize w;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
return w.ws_col;
if (ioctl(STDERR_FILENO, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
return w.ws_col;
if (ioctl(STDIN_FILENO, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
return w.ws_col;
const char *c = getenv("COLUMNS");
if (!c || !*c)
return 0;
char *endp;
long v = strtol(c, &endp, 10);
if (*endp != '\0' || v <= 0 || v > 100000)
return 0;
return (int)v;
}
static int json_terminal_width(const char *buf, jsmntok_t *t, int n) {
long v = jp_long(buf, t, n, "terminal_width", 0);
if (v > 0 && v <= 100000)
return (int)v;
return term_columns();
}
// Line 1: [Model] [·effort ✻] 📁 folder | 🌿 branch | [vim] [PR] [agent] [name]
static void pr_claude_line1(const char *buf, jsmntok_t *t, int n) {
seg_t segs[16];
memset(segs, 0, sizeof(segs));
int c = 0;
seg_t *s;
#define PUSH_SEG(prio_val, sep_val) \
(c < 16 ? (s = &segs[c++], s->prio = (prio_val), s->sep = (sep_val), s) : NULL)
// Model (always present; prio 0, no leading separator).
char model[256];
if (!jp_str(buf, t, n, "model.display_name", model, sizeof(model)))
snprintf(model, sizeof(model), "Unknown");
if (PUSH_SEG(0, SEP_NONE)) {
seg_color(s, WHT_F);
seg_addf(s, "[%s]", short_model(model));
seg_color(s, RST);
}
// Effort + extended-thinking, adjacent to the model name.
char effort[32];
int has_effort = jp_str(buf, t, n, "effort.level", effort, sizeof(effort)) && effort[0] != '\0';
int thinking = jp_bool(buf, t, n, "thinking.enabled", 0);
if (has_effort || thinking) {
if (PUSH_SEG(2, SEP_SPACE)) {
seg_color(s, DIM);
if (has_effort)
seg_addf(s, "\xC2\xB7%s", effort); // U+00B7 MIDDLE DOT
if (thinking) {
if (has_effort)
seg_addf(s, " ");
seg_addglyph(s, "\xE2\x9C\xBB", 1); // U+273B TEARDROP-SPOKED ASTERISK
}
seg_color(s, RST);
}
}
// Folder (basename), linked to the repo when supported.
char cur_dir[PATH_MAX_LEN] = "";
if (!jp_str(buf, t, n, "workspace.current_dir", cur_dir, sizeof(cur_dir)))
jp_str(buf, t, n, "cwd", cur_dir, sizeof(cur_dir));
if (cur_dir[0]) {
if (PUSH_SEG(0, SEP_SPACE)) {
seg_color(s, BRIGHT_BLU);
seg_addglyph(s, "\xF0\x9F\x93\x81", 2); // U+1F4C1 FOLDER
seg_addf(s, " ");
char host[128], owner[128], repo[128];
if (hyperlinks_ok() &&
jp_str(buf, t, n, "workspace.repo.host", host, sizeof(host)) &&
jp_str(buf, t, n, "workspace.repo.owner", owner, sizeof(owner)) &&
jp_str(buf, t, n, "workspace.repo.name", repo, sizeof(repo))) {
char url[512];
snprintf(url, sizeof(url), "https://%s/%s/%s", host, owner, repo);
seg_link(s, url, path_basename(cur_dir));
} else {
seg_addf(s, "%s", path_basename(cur_dir));
}
seg_color(s, RST);
}
char gd[PATH_MAX_LEN], wt[PATH_MAX_LEN];
if (find_git(cur_dir, gd, wt, sizeof(gd))) {
char br[256];
if (git_branch_name(gd, br, sizeof(br)) && br[0] != '\0') {
if (PUSH_SEG(1, SEP_PIPE)) {
seg_color(s, BRIGHT_CYN);
seg_addglyph(s, "\xF0\x9F\x8C\xBF", 2); // U+1F33F HERB