blob: 12df3b237da946bc2118ba95056b75d37a6546f1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
/*
 * The output every cgit page has in common. A link from one page to another is
 * built here because only this file knows whether a site addresses a request
 * as a path below a virtual root or as a query string, and the two are spelled
 * differently down to the separator between arguments. The headers, the
 * document head, the header block, the footer, the error page and the age
 * column are here so that a page handler is left with only its own body to
 * produce.
 */

#define USE_THE_REPOSITORY_VARIABLE

#include "cgit.h"
#include "html.h"
#include "shared.h"
#include "ui-shared.h"
#include "ui-snapshot.h"

#define DEFAULT_HTTP_PORT 80

#define SHORT_HASH_LEN 10

// A max-msg-len below this leaves too little of a commit subject to be worth
// truncating, and the ellipsis is paid for out of that same budget.
#define MIN_TRUNCATE_LEN 15
#define ELLIPSIS_LEN 3

// Lines of context git itself defaults to, which a link has no reason to name.
#define DEFAULT_DIFF_CONTEXT 3

// Bounds the breadcrumbs, so that one request cannot turn into an unbounded
// row of links.
#define MAX_CRUMB_LEVELS 15

// cgit_fmt exits the request rather than truncate, so a path is only worked
// into a tab title while it still leaves room to spare in that buffer.
#define MAX_TITLE_PATH_LEN 256

static const char *repo_basename(const char *reponame)
{
	// The result lives in a static buffer, so it is only good until the
	// next call.
	static char buf[1024];
	const char *slash;
	size_t len;
	int last;

	len = strlcpy(buf, reponame, sizeof(buf));
	if (len >= sizeof(buf))
		die("repo_basename: truncated repository name '%s'", reponame);
	last = len - 1;
	while (last && buf[last] == '/')
		buf[last--] = '\0';
	if (last >= 3 && starts_with(&buf[last - 3], ".git")) {
		last -= 3;
		buf[last--] = '\0';
	}
	while (last && buf[last] == '/')
		buf[last--] = '\0';
	slash = strrchr(buf, '/');
	if (slash)
		return ++slash;
	return buf;
}

static const char *root_url(void)
{
	if (ctx.cfg.virtual_root)
		return ctx.cfg.virtual_root;
	else
		return ctx.cfg.script_name;
}

static void site_url(const char *page, const char *search, const char *sort,
		     int ofs, int always_root)
{
	const char *delim = "?";

	if (always_root || page)
		html_attr(root_url());
	else {
		char *currenturl = cgit_currenturl();
		html_attr(currenturl);
		free(currenturl);
	}

	if (page) {
		htmlf("?p=%s", page);
		delim = "&";
	}
	if (search) {
		html(delim);
		html("q=");
		html_url_arg(search);
		delim = "&";
	}
	if (sort) {
		html(delim);
		html("s=");
		html_url_arg(sort);
		delim = "&";
	}
	if (ofs) {
		html(delim);
		htmlf("ofs=%d", ofs);
	}
}

static void site_link(const char *page, const char *name, const char *title,
		      const char *class, const char *search, const char *sort,
		      int ofs, int always_root)
{
	html("<a");
	if (title) {
		html(" title='");
		html_attr(title);
		html("'");
	}
	if (class) {
		html(" class='");
		html_attr(class);
		html("'");
	}
	html(" href='");
	site_url(page, search, sort, ofs, always_root);
	html("'>");
	html_txt(name);
	html("</a>");
}

/*
 * Open an anchor and write the part of its href naming the repository, the
 * page and the path, leaving the href quote open for the caller to add its own
 * arguments and close. The return is the delimiter to put before the first of
 * those, which is still a question mark unless a query string has been opened.
 */
static const char *repolink(const char *title, const char *class,
			    const char *page, const char *head,
			    const char *path)
{
	const char *delim = "?";

	html("<a");
	if (title) {
		html(" title='");
		html_attr(title);
		html("'");
	}
	if (class) {
		html(" class='");
		html_attr(class);
		html("'");
	}
	html(" href='");
	if (ctx.cfg.virtual_root) {
		html_url_path(ctx.cfg.virtual_root);
		html_url_path(ctx.repo->url);
		if (ctx.repo->url[strlen(ctx.repo->url) - 1] != '/')
			html("/");
		if (page) {
			html_url_path(page);
			html("/");
			if (path)
				html_url_path(path);
		}
	} else {
		html_url_path(ctx.cfg.script_name);
		html("?url=");
		html_url_arg(ctx.repo->url);
		if (ctx.repo->url[strlen(ctx.repo->url) - 1] != '/')
			html("/");
		if (page) {
			html_url_arg(page);
			html("/");
			if (path)
				html_url_arg(path);
		}
		delim = "&amp;";
	}
	if (head && ctx.repo->defbranch && strcmp(head, ctx.repo->defbranch)) {
		html(delim);
		html("h=");
		html_url_arg(head);
		delim = "&amp;";
	}
	return cgit_fmt("%s", delim);
}

static const char *emit_rev_arg(const char *delim, const char *rev)
{
	if (rev && ctx.qry.head && strcmp(rev, ctx.qry.head)) {
		html(delim);
		html("id=");
		html_url_arg(rev);
		return "&amp;";
	}
	return delim;
}

static void reporevlink(const char *page, const char *name, const char *title,
			const char *class, const char *head, const char *rev,
			const char *path)
{
	const char *delim;

	delim = repolink(title, class, page, head, path);
	emit_rev_arg(delim, rev);
	html("'>");
	html_txt(name);
	html("</a>");
}

static void emit_diff_args(const char *delim)
{
	if (ctx.qry.difftype) {
		html(delim);
		htmlf("dt=%d", ctx.qry.difftype);
		delim = "&amp;";
	}
	if (ctx.qry.context > 0 && ctx.qry.context != DEFAULT_DIFF_CONTEXT) {
		html(delim);
		html("context=");
		htmlf("%d", ctx.qry.context);
		delim = "&amp;";
	}
	if (ctx.qry.ignorews) {
		html(delim);
		html("ignorews=1");
		delim = "&amp;";
	}
	if (ctx.qry.follow) {
		html(delim);
		html("follow=1");
	}
}

static struct string_list_item *lookup_path(struct string_list *list,
					    const char *path)
{
	struct string_list_item *item;

	while (path && path[0]) {
		if ((item = string_list_lookup(list, path)))
			return item;
		if (!(path = strchr(path, '/')))
			break;
		path++;
	}
	return NULL;
}

/*
 * A repository can supply the module-link template through a repo-local
 * cgitrc, so the %s placeholders are expanded here instead of the template
 * being handed to printf, where a surplus conversion would read past the
 * argument list.
 */
static void emit_module_link(const char *tmpl, const char **args, int nargs)
{
	struct strbuf sb = STRBUF_INIT;
	int used = 0;

	while (*tmpl) {
		if (*tmpl != '%') {
			strbuf_addch(&sb, *tmpl++);
			continue;
		}
		tmpl++;
		if (*tmpl == '%') {
			strbuf_addch(&sb, '%');
			tmpl++;
		} else if (*tmpl == 's' && used < nargs) {
			strbuf_addstr(&sb, args[used++]);
			tmpl++;
		} else {
			strbuf_addch(&sb, '%');
		}
	}
	html_attr(sb.buf);
	strbuf_release(&sb);
}

static struct date_mode configured_date_mode(void)
{
	struct date_mode mode = ctx.cfg.date_mode;

	if (ctx.cfg.local_time)
		mode.local = 1;
	return mode;
}

/*
 * Dates render as time elements, whose datetime attribute wants the strict
 * ISO 8601 form with the T separator rather than the space git prints by
 * default.
 */
static void print_abs_date(time_t t, int tz)
{
	html("<time datetime='");
	html_attr(show_date(t, tz, cgit_date_mode(DATE_ISO8601_STRICT)));
	html("' title='");
	html_attr(show_date(t, tz, cgit_date_mode(DATE_ISO8601)));
	html("'>");
	html_txt(show_date(t, tz, configured_date_mode()));
	html("</time>");
}

static void print_rel_date(time_t t, int tz, double count, const char *class,
			   const char *suffix)
{
	htmlf("<time class='%s' datetime='", class);
	html_attr(show_date(t, tz, cgit_date_mode(DATE_ISO8601_STRICT)));
	htmlf("' data-ut='%" PRIu64 "' title='", (uint64_t)t);
	html_attr(show_date(t, tz, cgit_date_mode(DATE_ISO8601)));
	htmlf("'>%.0f %s</time>", count, suffix);
}

static char *http_date(time_t t)
{
	static char day[][4] =
		{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	static char month[][4] =
		{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
		 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	struct tm tm;
	gmtime_r(&t, &tm);
	return cgit_fmt("%s, %02d %s %04d %02d:%02d:%02d GMT", day[tm.tm_wday],
		   tm.tm_mday, month[tm.tm_mon], 1900 + tm.tm_year,
		   tm.tm_hour, tm.tm_min, tm.tm_sec);
}

static void print_rel_vcs_link(const char *url)
{
	html("<link rel='vcs-git' href='");
	html_attr(url);
	html("' title='");
	html_attr(ctx.repo->name);
	html(" Git repository'>\n");
}

static int emit_css_link(struct string_list_item *item, void *fallback)
{
	// An empty css entry is how a site turns the stylesheet off.
	if (item && *item->string == '\0')
		return 0;

	html("<link rel='stylesheet' href='");
	if (item)
		html_attr(item->string);
	else
		html_attr((const char *)fallback);
	html("'>\n");

	return 0;
}

static int emit_js_link(struct string_list_item *item, void *fallback)
{
	// An empty js entry is how a site turns the script off.
	if (item && *item->string == '\0')
		return 0;

	html("<script src='");
	if (item)
		html_attr(item->string);
	else
		html_attr((const char *)fallback);
	html("'></script>\n");

	return 0;
}

static void add_clone_urls(void (*fn)(const char *), char *urls, char *suffix)
{
	struct strbuf **url_list = strbuf_split_str(urls, ' ', 0);
	int i;

	for (i = 0; url_list[i]; i++) {
		strbuf_rtrim(url_list[i]);
		if (url_list[i]->len == 0)
			continue;
		if (suffix && *suffix)
			strbuf_addf(url_list[i], "/%s", suffix);
		fn(url_list[i]->buf);
	}

	strbuf_list_free(url_list);
}

static int print_branch_option(const struct reference *ref, void *counter)
{
	int *count = counter;
	const char *name = ref->name;
	// The switcher runs on every page, so it is bounded like the refs list.
	if (ctx.cfg.max_ref_count && *count >= ctx.cfg.max_ref_count)
		return -1;
	(*count)++;
	html_option(name, name, ctx.qry.head);
	return 0;
}

static void print_header(void)
{
	const char *logo = NULL, *logo_link = NULL;

	if (ctx.repo && ctx.repo->logo && *ctx.repo->logo)
		logo = ctx.repo->logo;
	else
		logo = ctx.cfg.logo;
	if (ctx.repo && ctx.repo->logo_link && *ctx.repo->logo_link)
		logo_link = ctx.repo->logo_link;
	else
		logo_link = ctx.cfg.logo_link;

	html("<header id='header'>\n");
	if (logo && *logo) {
		html("<a class='logo' href='");
		if (logo_link && *logo_link)
			html_attr(logo_link);
		else
			html_attr(root_url());
		html("'><img src='");
		html_attr(logo);
		html("' alt='cgit logo'></a>\n");
	}

	html("<h1 class='main'>");
	if (ctx.repo) {
		cgit_index_link("index", NULL, NULL, NULL, NULL, 0, 1);
		html(" : ");
		cgit_summary_link(ctx.repo->name, NULL, NULL, NULL);
	} else
		html_txt(ctx.cfg.root_title);
	html("</h1>\n");

	// A repository with no commits has no branches to list, so the
	// switcher would be an empty select next to a switch button.
	if (ctx.repo && ctx.env.authenticated && !ctx.empty_repo) {
		html("<form class='branch-switch' method='get'>\n");
		cgit_add_hidden_formfields(0, 1, ctx.qry.page);
		html("<select name='h' aria-label='Branch' data-autosubmit='1'>\n");
		int branch_count = 0;
		refs_for_each_branch_ref(get_main_ref_store(the_repository),
					 print_branch_option, &branch_count);
		if (ctx.repo->enable_remote_branches)
			refs_for_each_remote_ref(get_main_ref_store(the_repository),
						 print_branch_option, &branch_count);
		html("</select> ");
		html("<input type='submit' value='switch'>");
		html("</form>\n");
	}

	if (ctx.repo) {
		html("<p class='sub desc'>");
		html_txt(ctx.repo->desc);
		html("</p>\n");
		html("<p class='sub owner'>");
		html_txt(ctx.repo->owner);
		html("</p>\n");
	} else if (ctx.cfg.root_desc) {
		html("<p class='sub desc'>");
		html_txt(ctx.cfg.root_desc);
		html("</p>\n");
	}

	html("<button type='button' class='theme-toggle' hidden "
	     "aria-label='Toggle color theme'></button>\n");
	html("</header>\n");
}

static const char *tab_class(const char *page)
{
	if (!ctx.qry.page)
		return NULL;

	return strcmp(ctx.qry.page, page) ? NULL : "active";
}

static const char *tab_title(const char *format, const char *fallback,
			     const char *path)
{
	if (!path || !*path || strlen(path) > MAX_TITLE_PATH_LEN)
		return fallback;
	return cgit_fmt(format, path);
}

static void print_repo_tabs(void)
{
	const char *vpath = ctx.qry.vpath;

	html("<ul>\n");
	if (ctx.repo->readme.nr) {
		html("<li>");
		reporevlink("about", "about", "About this repository",
			    tab_class("about"), ctx.qry.head, NULL, NULL);
		html("</li>\n");
	}
	html("<li>");
	cgit_summary_link("summary", "Repository summary", tab_class("summary"),
			  ctx.qry.head);
	html("</li>\n<li>");
	cgit_refs_link("refs", "Branches and tags", tab_class("refs"),
		       ctx.qry.head, ctx.qry.oid, NULL);
	html("</li>\n<li>");
	cgit_log_link("log",
		      tab_title("Commit history of %s", "Commit history", vpath),
		      tab_class("log"), ctx.qry.head,
		      NULL, ctx.qry.vpath, 0, NULL, NULL,
		      ctx.qry.showmsg, ctx.qry.follow);
	html("</li>\n<li>");
	if (ctx.qry.page && !strcmp(ctx.qry.page, "blame"))
		cgit_blame_link("blame",
				tab_title("Line-by-line blame of %s", "Blame", vpath),
				tab_class("blame"), ctx.qry.head,
				ctx.qry.oid, ctx.qry.vpath);
	else
		cgit_tree_link("tree",
			       tab_title("Browse the tree at %s", "Browse the file tree", vpath),
			       tab_class("tree"), ctx.qry.head,
			       ctx.qry.oid, ctx.qry.vpath);
	html("</li>\n<li>");
	cgit_commit_link("commit", "The current commit", tab_class("commit"),
			 ctx.qry.head, ctx.qry.oid, ctx.qry.vpath);
	html("</li>\n<li>");
	cgit_diff_link("diff",
		       tab_title("Changes to %s", "Changes in the current commit", vpath),
		       tab_class("diff"), ctx.qry.head,
		       ctx.qry.oid, ctx.qry.oid2, ctx.qry.vpath);
	html("</li>\n");
	if (ctx.repo->enable_stats) {
		html("<li>");
		cgit_stats_link("stats", "Commit activity", tab_class("stats"),
				ctx.qry.head, ctx.qry.vpath);
		html("</li>\n");
	}
	html("</ul>\n");
}

static void print_repo_search(void)
{
	html("<form class='search' method='get' action='");
	if (ctx.cfg.virtual_root) {
		char *fileurl = cgit_fileurl(ctx.qry.repo, "log",
					     ctx.qry.vpath, NULL);
		html_url_path(fileurl);
		free(fileurl);
	}
	html("'>\n");
	cgit_add_hidden_formfields(1, 0, "log");
	html("<select name='qt' aria-label='Search type'>\n");
	html_option("grep", "log msg", ctx.qry.grep);
	html_option("author", "author", ctx.qry.grep);
	html_option("committer", "committer", ctx.qry.grep);
	html_option("range", "range", ctx.qry.grep);
	html("</select>\n");
	html("<input class='txt' type='search' name='q' aria-label='Search' value='");
	html_attr(ctx.qry.search);
	html("'>\n");
	html("<input type='submit' value='search'>\n");
	html("</form>\n");
}

static void print_site_tabs(void)
{
	html("<ul>\n<li>");
	site_link(NULL, "index", "Repository index", tab_class("repolist"),
		  NULL, NULL, 0, 1);
	html("</li>\n");
	if (ctx.cfg.root_readme) {
		html("<li>");
		site_link("about", "about", "About this site",
			  tab_class("about"), NULL, NULL, 0, 1);
		html("</li>\n");
	}
	html("</ul>\n");
}

static void print_site_search(void)
{
	char *currenturl = cgit_currenturl();

	html("<form class='search' method='get' action='");
	html_attr(currenturl);
	html("'>\n");
	html("<input class='txt' type='search' name='q' aria-label='Search' value='");
	html_attr(ctx.qry.search);
	html("'>\n");
	html("<input type='submit' value='search'>\n");
	html("</form>\n");
	free(currenturl);
}

// The link is built out of the request in ctx.qry, so a caller that alters a
// field of ctx.qry first gets a link differing in exactly that.
static void snapshot_link(const char *name, const char *title, const char *class,
			const char *head, const char *rev,
			const char *archivename)
{
	reporevlink("snapshot", name, title, class, head, rev, archivename);
}

static void self_link(const char *name, const char *title, const char *class)
{
	if (!strcmp(ctx.qry.page, "repolist"))
		cgit_index_link(name, title, class, ctx.qry.search, ctx.qry.sort,
				ctx.qry.ofs, 1);
	else if (!strcmp(ctx.qry.page, "summary"))
		cgit_summary_link(name, title, class, ctx.qry.head);
	else if (!strcmp(ctx.qry.page, "tag"))
		cgit_tag_link(name, title, class, ctx.qry.has_oid ?
			       ctx.qry.oid : ctx.qry.head);
	else if (!strcmp(ctx.qry.page, "tree"))
		cgit_tree_link(name, title, class, ctx.qry.head,
			       ctx.qry.has_oid ? ctx.qry.oid : NULL,
			       ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "plain"))
		cgit_plain_link(name, title, class, ctx.qry.head,
				ctx.qry.has_oid ? ctx.qry.oid : NULL,
				ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "blame"))
		cgit_blame_link(name, title, class, ctx.qry.head,
				ctx.qry.has_oid ? ctx.qry.oid : NULL,
				ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "log"))
		cgit_log_link(name, title, class, ctx.qry.head,
			      ctx.qry.has_oid ? ctx.qry.oid : NULL,
			      ctx.qry.path, ctx.qry.ofs,
			      ctx.qry.grep, ctx.qry.search,
			      ctx.qry.showmsg, ctx.qry.follow);
	else if (!strcmp(ctx.qry.page, "commit"))
		cgit_commit_link(name, title, class, ctx.qry.head,
				 ctx.qry.has_oid ? ctx.qry.oid : NULL,
				 ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "patch"))
		cgit_patch_link(name, title, class, ctx.qry.head,
				ctx.qry.has_oid ? ctx.qry.oid : NULL,
				ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "refs"))
		cgit_refs_link(name, title, class, ctx.qry.head,
			       ctx.qry.has_oid ? ctx.qry.oid : NULL,
			       ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "snapshot"))
		snapshot_link(name, title, class, ctx.qry.head,
				   ctx.qry.has_oid ? ctx.qry.oid : NULL,
				   ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "diff"))
		cgit_diff_link(name, title, class, ctx.qry.head,
			       ctx.qry.oid, ctx.qry.oid2,
			       ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "stats"))
		cgit_stats_link(name, title, class, ctx.qry.head,
				ctx.qry.path);
	else {
		// A page name this switch does not know still gets a plain
		// repolink, which covers any simple page added later.
		repolink(title, class, ctx.qry.page, ctx.qry.head, ctx.qry.path);
		html("'>");
		html_txt(name);
		html("</a>");
	}
}

static void print_path_crumbs(char *path)
{
	char *old_path = ctx.qry.path;
	char *start = path, *slash, *end = path + strlen(path);
	int levels = 0;

	ctx.qry.path = NULL;
	self_link("root", NULL, NULL);
	// self_link reads the path out of ctx.qry, so terminating the buffer at
	// each slash is what makes a crumb link to the prefix it stands for.
	ctx.qry.path = start = path;
	while (start < end) {
		if (!(slash = strchr(start, '/')) || levels > MAX_CRUMB_LEVELS)
			slash = end;
		*slash = '\0';
		html_txt("/");
		self_link(start, NULL, NULL);
		if (slash < end)
			*slash = '/';
		start = slash + 1;
		++levels;
	}
	ctx.qry.path = old_path;
}

// A reverse memchr, which glibc has as memrchr but macOS and the BSDs do not.
static const char *find_last_char(const char *start, const char *end, int c)
{
	while (end > start) {
		if (*--end == c)
			return end;
	}
	return NULL;
}

static void vprint_error(const char *fmt, va_list ap)
{
	va_list cp;
	html("<div class='error'>");
	va_copy(cp, ap);
	html_vtxtf(fmt, cp);
	va_end(cp);
	html("</div>\n");
}

void cgit_print_error(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	vprint_error(fmt, ap);
	va_end(ap);
}

const char *cgit_httpscheme(void)
{
	if (ctx.env.https && !strcmp(ctx.env.https, "on"))
		return "https://";
	else
		return "http://";
}

char *cgit_hosturl(void)
{
	if (ctx.env.http_host)
		return xstrdup(ctx.env.http_host);
	if (!ctx.env.server_name)
		return NULL;
	if (!ctx.env.server_port ||
	    atoi(ctx.env.server_port) == DEFAULT_HTTP_PORT)
		return xstrdup(ctx.env.server_name);
	return cgit_fmtalloc("%s:%s", ctx.env.server_name, ctx.env.server_port);
}

char *cgit_currenturl(void)
{
	const char *root = root_url();

	if (!ctx.qry.url)
		return xstrdup(root);
	if (root[0] && root[strlen(root) - 1] == '/')
		return cgit_fmtalloc("%s%s", root, ctx.qry.url);
	return cgit_fmtalloc("%s/%s", root, ctx.qry.url);
}

char *cgit_currentfullurl(void)
{
	const char *root = root_url();
	const char *orig_query = ctx.env.query_string ? ctx.env.query_string : "";
	size_t len = strlen(orig_query);
	char *query = xmalloc(len + 2);
	char *match, *ret;

	// The url argument carried the path into this request and the path is
	// spelled out again below, so it is dropped here. The copy keeps a
	// leading question mark so that every match has a character before it,
	// which is what tells the argument itself from the tail of another one.
	memcpy(query + 1, orig_query, len + 1);
	query[0] = '?';
	match = query;
	while ((match = strstr(match, "url=")) != NULL) {
		if (match[-1] == '?' || match[-1] == '&') {
			const char *next = strchr(match, '&');
			if (next)
				memmove(match, next + 1, strlen(next));
			else
				match[0] = '\0';
		} else
			++match;
	}
	if (!query[1])
		query[0] = '\0';

	if (!ctx.qry.url)
		ret = cgit_fmtalloc("%s%s", root, query);
	else if (root[0] && root[strlen(root) - 1] == '/')
		ret = cgit_fmtalloc("%s%s%s", root, ctx.qry.url, query);
	else
		ret = cgit_fmtalloc("%s/%s%s", root, ctx.qry.url, query);
	free(query);
	return ret;
}

const char *cgit_loginurl(void)
{
	static const char *login_url;
	if (!login_url)
		login_url = cgit_fmtalloc("%s?p=login", root_url());
	return login_url;
}

char *cgit_repourl(const char *reponame)
{
	if (ctx.cfg.virtual_root)
		return cgit_fmtalloc("%s%s/", ctx.cfg.virtual_root, reponame);
	else
		return cgit_fmtalloc("?r=%s", reponame);
}

char *cgit_fileurl(const char *reponame, const char *pagename,
		   const char *filename, const char *query)
{
	struct strbuf sb = STRBUF_INIT;
	const char *delim;

	// The result is a raw URL, so the query joiner is a bare ampersand
	// and each sink escapes the whole string for wherever it lands.
	if (ctx.cfg.virtual_root) {
		strbuf_addf(&sb, "%s%s/%s/%s", ctx.cfg.virtual_root, reponame,
			    pagename, (filename ? filename:""));
		delim = "?";
	} else {
		strbuf_addf(&sb, "?url=%s/%s/%s", reponame, pagename,
			    (filename ? filename : ""));
		delim = "&";
	}
	if (query)
		strbuf_addf(&sb, "%s%s", delim, query);
	return strbuf_detach(&sb, NULL);
}

char *cgit_pageurl(const char *reponame, const char *pagename,
		   const char *query)
{
	return cgit_fileurl(reponame, pagename, NULL, query);
}

const char *cgit_snapshot_prefix(const struct cgit_repo *repo)
{
	if (repo->snapshot_prefix)
		return repo->snapshot_prefix;

	return repo_basename(repo->url);
}

void cgit_index_link(const char *name, const char *title, const char *class,
		     const char *pattern, const char *sort, int ofs,
		     int always_root)
{
	site_link(NULL, name, title, class, pattern, sort, ofs, always_root);
}

void cgit_summary_link(const char *name, const char *title, const char *class,
		       const char *head)
{
	reporevlink(NULL, name, title, class, head, NULL, NULL);
}

void cgit_tag_link(const char *name, const char *title, const char *class,
		   const char *tag)
{
	reporevlink("tag", name, title, class, tag, NULL, NULL);
}

void cgit_tree_link(const char *name, const char *title, const char *class,
		    const char *head, const char *rev, const char *path)
{
	reporevlink("tree", name, title, class, head, rev, path);
}

void cgit_plain_link(const char *name, const char *title, const char *class,
		     const char *head, const char *rev, const char *path)
{
	reporevlink("plain", name, title, class, head, rev, path);
}

void cgit_blame_link(const char *name, const char *title, const char *class,
		     const char *head, const char *rev, const char *path)
{
	reporevlink("blame", name, title, class, head, rev, path);
}

void cgit_log_link(const char *name, const char *title, const char *class,
		   const char *head, const char *rev, const char *path,
		   int ofs, const char *grep, const char *pattern, int showmsg,
		   int follow)
{
	const char *delim;

	delim = repolink(title, class, "log", head, path);
	delim = emit_rev_arg(delim, rev);
	if (grep && pattern) {
		html(delim);
		html("qt=");
		html_url_arg(grep);
		delim = "&amp;";
		html(delim);
		html("q=");
		html_url_arg(pattern);
	}
	if (ofs > 0) {
		html(delim);
		html("ofs=");
		htmlf("%d", ofs);
		delim = "&amp;";
	}
	if (showmsg) {
		html(delim);
		html("showmsg=1");
		delim = "&amp;";
	}
	if (follow) {
		html(delim);
		html("follow=1");
	}
	html("'>");
	html_txt(name);
	html("</a>");
}

void cgit_commit_link(const char *name, const char *title, const char *class,
		      const char *head, const char *rev, const char *path)
{
	const char *delim;

	delim = repolink(title, class, "commit", head, path);
	delim = emit_rev_arg(delim, rev);
	emit_diff_args(delim);
	html("'>");
	if (name && name[0] != '\0') {
		if (ctx.cfg.max_msg_len >= MIN_TRUNCATE_LEN &&
		    strlen(name) > (size_t)ctx.cfg.max_msg_len) {
			html_ntxt(name, ctx.cfg.max_msg_len - ELLIPSIS_LEN);
			html("...");
		} else
			html_txt(name);
	} else
		html_txt("(no commit message)");
	html("</a>");
}

void cgit_refs_link(const char *name, const char *title, const char *class,
		    const char *head, const char *rev, const char *path)
{
	reporevlink("refs", name, title, class, head, rev, path);
}

void cgit_diff_link(const char *name, const char *title, const char *class,
		    const char *head, const char *new_rev, const char *old_rev,
		    const char *path)
{
	const char *delim;

	delim = repolink(title, class, "diff", head, path);
	delim = emit_rev_arg(delim, new_rev);
	if (old_rev) {
		html(delim);
		html("id2=");
		html_url_arg(old_rev);
		delim = "&amp;";
	}
	emit_diff_args(delim);
	html("'>");
	html_txt(name);
	html("</a>");
}

void cgit_patch_link(const char *name, const char *title, const char *class,
		     const char *head, const char *rev, const char *path)
{
	reporevlink("patch", name, title, class, head, rev, path);
}

void cgit_stats_link(const char *name, const char *title, const char *class,
		     const char *head, const char *path)
{
	reporevlink("stats", name, title, class, head, NULL, path);
}

void cgit_object_link(struct object *obj)
{
	const char *page;
	char *shortrev, *fullrev, *name;

	fullrev = oid_to_hex(&obj->oid);
	shortrev = xstrdup(fullrev);
	shortrev[SHORT_HASH_LEN] = '\0';
	if (obj->type == OBJ_COMMIT) {
		cgit_commit_link(cgit_fmt("commit %s...", shortrev), NULL, NULL,
				 ctx.qry.head, fullrev, NULL);
		return;
	} else if (obj->type == OBJ_TREE)
		page = "tree";
	else if (obj->type == OBJ_TAG)
		page = "tag";
	else
		page = "blob";
	name = cgit_fmt("%s %s...", type_name(obj->type), shortrev);
	reporevlink(page, name, NULL, NULL, ctx.qry.head, fullrev, NULL);
}

void cgit_submodule_link(const char *class, char *path, const char *rev)
{
	struct string_list *list;
	struct string_list_item *item;
	char tail, *dir;
	size_t len;

	len = 0;
	tail = 0;
	list = &ctx.repo->submodules;
	item = lookup_path(list, path);
	if (!item) {
		len = strlen(path);
		tail = path[len - 1];
		if (tail == '/') {
			path[len - 1] = 0;
			item = lookup_path(list, path);
		}
	}
	if (item || ctx.repo->module_link) {
		html("<a ");
		if (class)
			htmlf("class='%s' ", class);
		html("href='");
		if (item) {
			const char *args[] = { rev };
			emit_module_link(item->util, args, 1);
		} else {
			const char *args[2];
			dir = strrchr(path, '/');
			if (dir)
				dir++;
			else
				dir = path;
			args[0] = dir;
			args[1] = rev;
			emit_module_link(ctx.repo->module_link, args, 2);
		}
		html("'>");
		html_txt(path);
		html("</a>");
	} else {
		html("<span");
		if (class)
			htmlf(" class='%s'", class);
		html(">");
		html_txt(path);
		html("</span>");
	}
	html_txtf(" @ %.7s", rev);
	if (item && tail)
		path[len - 1] = tail;
}

struct date_mode cgit_date_mode(enum date_mode_type type)
{
	static struct date_mode mode;
	mode.type = type;
	mode.local = ctx.cfg.local_time;
	return mode;
}

void cgit_print_age(time_t t, int tz, time_t max_relative)
{
	time_t now, secs;

	if (!t)
		return;
	time(&now);
	secs = now - t;
	if (secs < 0)
		secs = 0;

	if (!ctx.cfg.enable_relative_dates ||
	    (secs > max_relative && max_relative >= 0)) {
		print_abs_date(t, tz);
		return;
	}

	if (secs < SECONDS_PER_HOUR * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_MINUTE,
			       "age-mins", "min.");
		return;
	}
	if (secs < SECONDS_PER_DAY * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_HOUR,
			       "age-hours", "hours");
		return;
	}
	if (secs < SECONDS_PER_WEEK * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_DAY,
			       "age-days", "days");
		return;
	}
	if (secs < SECONDS_PER_MONTH * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_WEEK,
			       "age-weeks", "weeks");
		return;
	}
	if (secs < SECONDS_PER_YEAR * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_MONTH,
			       "age-months", "months");
		return;
	}
	print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_YEAR,
		       "age-years", "years");
}

void cgit_print_http_headers(void)
{
	if (ctx.env.no_http && !strcmp(ctx.env.no_http, "1"))
		return;

	if (ctx.page.status)
		htmlf("Status: %d %s\n", ctx.page.status, ctx.page.statusmsg);
	if (ctx.page.mimetype && ctx.page.charset)
		htmlf("Content-Type: %s; charset=%s\n", ctx.page.mimetype,
		      ctx.page.charset);
	else if (ctx.page.mimetype)
		htmlf("Content-Type: %s\n", ctx.page.mimetype);
	if (ctx.page.size)
		htmlf("Content-Length: %zd\n", ctx.page.size);
	if (ctx.page.filename) {
		html("Content-Disposition: inline; filename=\"");
		html_header_arg_in_quotes(ctx.page.filename);
		html("\"\n");
	}
	if (!ctx.env.authenticated)
		html("Cache-Control: no-cache, no-store\n");
	htmlf("Last-Modified: %s\n", http_date(ctx.page.modified));
	htmlf("Expires: %s\n", http_date(ctx.page.expires));
	if (ctx.page.etag)
		htmlf("ETag: \"%s\"\n", ctx.page.etag);
	html("\n");
	// Some pages follow the headers with output written by git itself, not
	// through html_raw, so the buffer is emptied to keep the headers first.
	html_flush();
	if (ctx.env.request_method && !strcmp(ctx.env.request_method, "HEAD"))
		exit(0);
}

void cgit_redirect(const char *url, bool permanent)
{
	htmlf("Status: %d %s\n", permanent ? 301 : 302, permanent ? "Moved" : "Found");
	html("Location: ");
	html_url_path(url);
	html("\n\n");
}

void cgit_print_docstart(void)
{
	char *host = cgit_hosturl();

	if (ctx.cfg.embedded) {
		if (ctx.cfg.header)
			html_include(ctx.cfg.header);
		return;
	}

	html("<!DOCTYPE html>\n");
	html("<html lang='en' class='cgit-standalone'>\n");
	html("<head>\n");
	html("<meta charset='utf-8'>\n");
	html("<meta name='viewport' content='width=device-width, initial-scale=1'>\n");
	html("<meta name='color-scheme' content='light dark'>\n");
	html("<meta name='theme-color' media='(prefers-color-scheme: light)' content='#ffffff'>\n");
	html("<meta name='theme-color' media='(prefers-color-scheme: dark)' content='#1b1b1b'>\n");
	html("<title>");
	// An error page reached before a title was chosen still has to name
	// itself, since an empty title element is not valid.
	html_txt(ctx.page.title ? ctx.page.title : ctx.cfg.root_title);
	html("</title>\n");
	htmlf("<meta name='generator' content='cgit %s'>\n", cgit_version);
	if (ctx.cfg.robots && *ctx.cfg.robots) {
		html("<meta name='robots' content='");
		html_attr(ctx.cfg.robots);
		html("'>\n");
	}

	if (ctx.cfg.css.items)
		for_each_string_list(&ctx.cfg.css, emit_css_link, NULL);
	else
		emit_css_link(NULL, "/cgit.css");

	if (ctx.cfg.js.items)
		for_each_string_list(&ctx.cfg.js, emit_js_link, NULL);
	else
		emit_js_link(NULL, "/cgit.js");

	if (ctx.cfg.favicon && *ctx.cfg.favicon) {
		html("<link rel='icon' href='");
		html_attr(ctx.cfg.favicon);
		html("'>\n");
	}
	if (host && ctx.repo && ctx.qry.head) {
		char *fileurl;
		struct strbuf sb = STRBUF_INIT;
		strbuf_addf(&sb, "h=%s", ctx.qry.head);

		html("<link rel='alternate' title='Atom feed' href='");
		html(cgit_httpscheme());
		html_attr(host);
		fileurl = cgit_fileurl(ctx.repo->url, "atom", ctx.qry.vpath,
				       sb.buf);
		html_attr(fileurl);
		html("' type='application/atom+xml'>\n");
		strbuf_release(&sb);
		free(fileurl);
	}
	if (ctx.repo)
		cgit_add_clone_urls(print_rel_vcs_link);
	if (ctx.cfg.head_include)
		html_include(ctx.cfg.head_include);
	if (ctx.repo && ctx.repo->extra_head_content)
		html(ctx.repo->extra_head_content);
	html("</head>\n");
	html("<body>\n");
	if (ctx.cfg.header)
		html_include(ctx.cfg.header);
	free(host);
}

void cgit_print_docend(void)
{
	html("</main>\n");
	if (ctx.cfg.embedded) {
		html("</div>\n");
		if (ctx.cfg.footer)
			html_include(ctx.cfg.footer);
		return;
	}
	if (ctx.cfg.footer)
		html_include(ctx.cfg.footer);
	else {
		htmlf("<footer class='footer'>generated by <a href='https://github.com/brycekwon/cgit'>cgit %s</a> "
			"(<a href='https://git-scm.com/'>git %s</a>) at ", cgit_version, git_version_string);
		html_txt(show_date(time(NULL), 0, cgit_date_mode(DATE_ISO8601)));
		html("</footer>\n");
	}
	html("</div>\n");
	html("</body>\n</html>\n");
}

void cgit_print_error_page(int code, const char *msg, const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	cgit_vprint_error_page(code, msg, fmt, ap);
	va_end(ap);
}

void cgit_vprint_error_page(int code, const char *msg, const char *fmt,
			    va_list ap)
{
	ctx.page.expires = ctx.cfg.cache_dynamic_ttl;
	ctx.page.status = code;
	ctx.page.statusmsg = msg;
	cgit_print_layout_start();
	vprint_error(fmt, ap);
	cgit_print_layout_end();
}

void cgit_print_layout_start(void)
{
	cgit_print_http_headers();
	cgit_print_docstart();
	cgit_print_pageheader();
}

void cgit_print_layout_end(void)
{
	cgit_print_docend();
}

void cgit_add_clone_urls(void (*fn)(const char *))
{
	if (ctx.repo->clone_url)
		add_clone_urls(fn, cgit_expand_macros(ctx.repo->clone_url), NULL);
	else if (ctx.cfg.clone_prefix)
		add_clone_urls(fn, ctx.cfg.clone_prefix, ctx.repo->url);
}

void cgit_add_hidden_formfields(int incl_head, int incl_search,
				const char *page)
{
	if (!ctx.cfg.virtual_root) {
		struct strbuf url = STRBUF_INIT;

		strbuf_addf(&url, "%s/%s", ctx.qry.repo, page);
		if (ctx.qry.vpath)
			strbuf_addf(&url, "/%s", ctx.qry.vpath);
		html_hidden("url", url.buf);
		strbuf_release(&url);
	}

	if (incl_head && ctx.qry.head && ctx.repo->defbranch &&
	    strcmp(ctx.qry.head, ctx.repo->defbranch))
		html_hidden("h", ctx.qry.head);

	if (ctx.qry.oid)
		html_hidden("id", ctx.qry.oid);
	if (ctx.qry.oid2)
		html_hidden("id2", ctx.qry.oid2);
	if (ctx.qry.showmsg)
		html_hidden("showmsg", "1");

	if (incl_search) {
		if (ctx.qry.grep)
			html_hidden("qt", ctx.qry.grep);
		if (ctx.qry.search)
			html_hidden("q", ctx.qry.search);
	}
}

void cgit_print_pageheader(void)
{
	html("<div id='cgit'>\n");
	if (!ctx.env.authenticated || !ctx.cfg.noheader)
		print_header();

	if (ctx.env.authenticated)
		html("<nav class='tabs'>\n");
	if (ctx.env.authenticated && ctx.repo && ctx.empty_repo) {
		// Every other tab needs a commit to render and the search form
		// has nothing to search, so an empty repo gets summary alone.
		html("<ul>\n<li>");
		cgit_summary_link("summary", "Repository summary",
				  tab_class("summary"), ctx.qry.head);
		html("</li>\n</ul>\n");
	} else if (ctx.env.authenticated && ctx.repo) {
		print_repo_tabs();
		print_repo_search();
	} else if (ctx.env.authenticated) {
		print_site_tabs();
		print_site_search();
	}
	if (ctx.env.authenticated)
		html("</nav>\n");
	if (ctx.env.authenticated && ctx.repo && ctx.qry.vpath) {
		html("<nav class='path' aria-label='breadcrumb'>");
		html("path: ");
		print_path_crumbs(ctx.qry.vpath);
		if (ctx.repo->enable_follow_links && !strcmp(ctx.qry.page, "log")) {
			html(" (");
			ctx.qry.follow = !ctx.qry.follow;
			self_link(ctx.qry.follow ? "follow" : "unfollow",
				  NULL, NULL);
			ctx.qry.follow = !ctx.qry.follow;
			html(")");
		}
		html("</nav>\n");
	}
	html("<main class='content'>\n");
}

void cgit_print_filemode(unsigned short mode)
{
	if (S_ISDIR(mode))
		html("d");
	else if (S_ISLNK(mode))
		html("l");
	else if (S_ISGITLINK(mode))
		html("m");
	else
		html("-");
	html_fileperm(mode >> 6);
	html_fileperm(mode >> 3);
	html_fileperm(mode);
}

static void compose_snapshot_prefix(struct strbuf *filename, const char *base,
				  const char *ref)
{
	struct object_id oid;

	// A tag named v1.2 or V1.2 gives its snapshot the prettier name 1.2,
	// but only where dropping the letter cannot land two different tags on
	// one name, so that a snapshot can still be traced back to the tag it
	// was made from.
	if (repo_get_oid(the_repository, cgit_fmt("refs/tags/%s", ref), &oid) == 0 &&
	    (ref[0] == 'v' || ref[0] == 'V') && isdigit((unsigned char)ref[1]) &&
	    ((repo_get_oid(the_repository, cgit_fmt("refs/tags/%s", ref + 1), &oid) == 0) +
	     (repo_get_oid(the_repository, cgit_fmt("refs/tags/v%s", ref + 1), &oid) == 0) +
	     (repo_get_oid(the_repository, cgit_fmt("refs/tags/V%s", ref + 1), &oid) == 0) == 1))
		ref++;

	strbuf_addf(filename, "%s-%s", base, ref);
}

void cgit_print_snapshot_links(const struct cgit_repo *repo, const char *ref,
			       const char *separator)
{
	const struct cgit_snapshot_format *f;
	struct strbuf filename = STRBUF_INIT;
	const char *basename;
	size_t prefixlen;

	basename = cgit_snapshot_prefix(repo);
	if (starts_with(ref, basename))
		strbuf_addstr(&filename, ref);
	else
		compose_snapshot_prefix(&filename, basename, ref);

	prefixlen = filename.len;
	for (f = cgit_snapshot_formats; f->suffix; f++) {
		if (!(repo->snapshots & cgit_snapshot_format_bit(f)))
			continue;
		strbuf_setlen(&filename, prefixlen);
		strbuf_addstr(&filename, f->suffix);
		snapshot_link(filename.buf, NULL, NULL, NULL, NULL,
				   filename.buf);
		if (cgit_snapshot_get_sig(ref, f)) {
			strbuf_addstr(&filename, ".asc");
			html(" (");
			snapshot_link("sig", NULL, NULL, NULL, NULL,
					   filename.buf);
			html(")");
		} else if (starts_with(f->suffix, ".tar") && cgit_snapshot_get_sig(ref, &cgit_snapshot_formats[0])) {
			// A compressed tarball offers the signature made for
			// the plain tar it expands to, which is the first
			// format in the table.
			strbuf_setlen(&filename,
				      filename.len - strlen(f->suffix));
			strbuf_addstr(&filename, ".tar.asc");
			html(" (");
			snapshot_link("sig", NULL, NULL, NULL, NULL,
					   filename.buf);
			html(")");
		}
		html(separator);
	}
	strbuf_release(&filename);
}

void cgit_set_title_from_path(const char *path)
{
	struct strbuf sb = STRBUF_INIT;
	const char *slash, *last_slash;

	if (!path)
		return;

	// The path is read from the end so that the title names the file first
	// and the directories it sits in after it. The separator between them
	// is a guillemet, spelled here as the UTF-8 bytes of one.
	last_slash = path + strlen(path);
	while ((slash = find_last_char(path, last_slash, '/')) != NULL) {
		strbuf_add(&sb, slash + 1, last_slash - slash - 1);
		strbuf_addstr(&sb, " \xc2\xab ");
		last_slash = slash;
	}
	strbuf_add(&sb, path, last_slash - path);
	strbuf_addf(&sb, " - %s", ctx.page.title);
	ctx.page.title = strbuf_detach(&sb, NULL);
}