-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-md-split-preview.user.js
More file actions
1914 lines (1716 loc) · 79 KB
/
Copy pathgithub-md-split-preview.user.js
File metadata and controls
1914 lines (1716 loc) · 79 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
// ==UserScript==
// @name GitHub MD Split Preview
// @namespace https://github.com/lucidash
// @version 2.10.1
// @description GitHub PR/commit/compare의 변경 파일 화면에서 마크다운 diff와 렌더링 결과를 좌우 2단으로 동시에 보여주고 스크롤을 동기화합니다.
// @author muzi
// @homepageURL https://github.com/tpcint/gh-md-split-preview
// @supportURL https://github.com/tpcint/gh-md-split-preview/issues
// @updateURL https://raw.githubusercontent.com/tpcint/gh-md-split-preview/main/github-md-split-preview.user.js
// @downloadURL https://raw.githubusercontent.com/tpcint/gh-md-split-preview/main/github-md-split-preview.user.js
// @match https://github.com/*/*/pull/*
// @match https://github.com/*/*/commit/*
// @match https://github.com/*/*/commits/*
// @match https://github.com/*/*/compare/*
// @require https://cdn.jsdelivr.net/npm/marked@15/marked.min.js
// @require https://cdn.jsdelivr.net/gh/tpcint/gh-md-split-preview@mermaid-vendor-11.16.1/vendor/mermaid.min.js
// @grant GM_addStyle
// @run-at document-idle
// @noframes
// ==/UserScript==
/*
* 동작 원리
* ---------
* 1. diff DOM 에 이미 들어있는 "변경 후(after)" 라인을 긁어 마크다운 원문을 복원한다.
* 네트워크 요청이 전혀 없으므로 private repo / GHE / rate limit 문제가 없다.
* 2. marked 의 lexer 로 블록 토큰을 뽑고, 각 토큰의 raw 길이로 시작/끝 라인을 계산해
* 렌더링된 블록마다 data-line 을 심는다.
* 3. 좌(diff)/우(rendered) 양쪽에 [라인번호 → 스크롤 오프셋] 앵커를 만들고 선형 보간으로 동기화한다.
* 4. 추가(+)된 라인을 포함하는 렌더링 블록은 왼쪽에 초록 바로 강조한다.
* 5. ```mermaid 코드블록은 렌더 후 mermaid 로 SVG 를 그려 끼워 넣는다(실패하면 코드블록 그대로).
*
* mermaid 는 왜 vendor/ 사본인가
* ----------------------------
* 업스트림 브라우저 번들(dist/mermaid.min.js)은 최상위에 var 를 두고 마지막 줄에서 그걸
* globalThis 경유로 되읽어 전역 mermaid 를 만든다. Tampermonkey 는 @require 내용을 함수
* 스코프에서 실행하므로 그 var 가 지역변수가 되고, 마지막 줄이 undefined 를 읽어 로드
* 시점에 TypeError 를 던진다 — 그 위치가 본문보다 앞이라 2단 보기 자체가 뜨지 않는다.
* 11.x 전 릴리스가 같은 형태이고 "use strict" 라 @resource + 간접 eval 로도 못 피한다.
* vendor/mermaid.min.js 는 그 한 줄만 고친 사본이다 (tools/vendor-mermaid.mjs 로 갱신).
*
* 지원 DOM
* --------
* - 현행 React diff : tr.diff-line-row / td.diff-text-cell / .diff-text-inner / data-diff-line-key
* - 구형 Rails diff : [data-code-marker] / td.blob-num[data-line-number] (GHE 등 폴백)
*
* 한계
* ----
* - GitHub 이 접어둔 구간은 diff DOM 에 없으므로 렌더링에서도 빠진다(Expand 하면 자동 반영).
* - 펜스가 diff 밖이라 조각만 남은 mermaid 는 문법이 온전하지 않으므로 그리지 않고 코드로 둔다.
* - math 등 나머지 GitHub 전용 위젯은 그리지 않는다 — ```math 펜스는 코드블록으로, $$…$$ 는 원문 텍스트로 나온다.
*/
(function () {
'use strict';
const MD = typeof marked !== 'undefined' ? marked : (typeof window !== 'undefined' ? window.marked : null);
if (!MD) {
console.error('[md-split] marked 로드 실패 — @require 를 확인하세요.');
return;
}
MD.setOptions({ gfm: true, breaks: false });
const MD_EXT = /\.(md|markdown|mdx)$/i;
const STORAGE_KEY = 'mdsp:enabled';
const RATIO_KEY = 'mdsp:ratio';
const DEBUG = false;
const log = (...a) => DEBUG && console.debug('[md-split]', ...a);
const cfg = {
get enabled() { return localStorage.getItem(STORAGE_KEY) !== '0'; },
set enabled(v) { localStorage.setItem(STORAGE_KEY, v ? '1' : '0'); },
get ratio() {
const r = parseFloat(localStorage.getItem(RATIO_KEY));
return Number.isFinite(r) && r > 0.15 && r < 0.85 ? r : 0.5;
},
set ratio(v) { localStorage.setItem(RATIO_KEY, String(v)); },
};
// ────────────────────────────────────────────────────────────────── 스타일
GM_addStyle(`
.mdsp-bar {
display: flex; align-items: center; gap: 8px;
padding: 5px 12px; font-size: 12px;
border: 1px solid var(--borderColor-default, #30363d); border-bottom: 0;
background: var(--bgColor-muted, #161b22);
color: var(--fgColor-muted, #8b949e);
}
.mdsp-btn {
cursor: pointer; border: 1px solid var(--borderColor-default, #30363d);
background: var(--bgColor-default, #0d1117); color: inherit;
border-radius: 6px; padding: 2px 8px; font: inherit; line-height: 18px;
}
.mdsp-btn:hover { background: var(--bgColor-neutral-muted, rgba(110,118,129,.2)); }
.mdsp-btn[aria-pressed="true"] {
background: var(--bgColor-accent-emphasis, #1f6feb); color: #fff;
border-color: var(--bgColor-accent-emphasis, #1f6feb);
}
.mdsp-note { margin-left: auto; font-size: 11px; opacity: .85; }
.mdsp-wrap { display: flex; align-items: stretch; width: 100%; }
.mdsp-left, .mdsp-right { overflow: auto; min-width: 0; max-height: 82vh; }
.mdsp-left { flex: 0 0 auto; }
.mdsp-right {
flex: 1 1 auto; padding: 16px 20px;
border: 1px solid var(--borderColor-default, #30363d); border-left: 0;
border-radius: 0 0 6px 0;
background: var(--bgColor-default, #0d1117);
}
.mdsp-resizer { flex: 0 0 5px; cursor: col-resize; background: var(--borderColor-default, #30363d); }
.mdsp-resizer:hover, .mdsp-resizing .mdsp-resizer { background: var(--bgColor-accent-emphasis, #1f6feb); }
.mdsp-resizing { user-select: none; }
.mdsp-block { position: relative; }
.mdsp-block > :first-child { margin-top: 0; }
.mdsp-block > :last-child { margin-bottom: 0; }
.mdsp-block + .mdsp-block { margin-top: 12px; }
.mdsp-block[data-changed="1"] {
padding-left: 10px; margin-left: -13px;
border-left: 3px solid var(--bgColor-success-emphasis, #238636);
background: var(--bgColor-success-muted, rgba(46,160,67,.10));
border-radius: 0 4px 4px 0;
}
/* YAML frontmatter 표 (GitHub 과 동일하게 표로 보여준다) */
.mdsp-right .markdown-body .mdsp-fm { margin-bottom: 16px; }
.mdsp-right .markdown-body .mdsp-fm table {
display: table; width: 100%; border-collapse: collapse; font-size: 12px;
border: 1px solid var(--borderColor-default, #30363d); border-radius: 6px;
}
.mdsp-right .markdown-body .mdsp-fm td {
padding: 4px 10px; vertical-align: top;
border: 0; border-bottom: 1px solid var(--borderColor-muted, #21262d);
}
.mdsp-right .markdown-body .mdsp-fm tr:last-child td { border-bottom: 0; }
.mdsp-right .markdown-body .mdsp-fm td:first-child {
width: 1%; white-space: nowrap; font-weight: 600;
color: var(--fgColor-muted, #8b949e);
border-right: 1px solid var(--borderColor-muted, #21262d);
}
/* 배열·중첩 객체는 셀 안에서 다시 표로 편다 */
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-sub {
display: table; width: auto; margin: 0; border-radius: 0;
border: 0; border-collapse: collapse;
}
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-sub td,
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-sub th,
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-sub td:first-child,
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-sub th:first-child {
width: auto; white-space: normal; padding: 3px 8px;
color: inherit; font-weight: 400; text-align: left;
border: 1px solid var(--borderColor-muted, #21262d);
box-shadow: none;
}
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-sub th,
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-sub th:first-child {
font-weight: 600; color: var(--fgColor-muted, #8b949e);
}
.mdsp-right .markdown-body .mdsp-fm tr[data-changed="1"] {
background: var(--bgColor-success-muted, rgba(46,160,67,.10));
}
.mdsp-right .markdown-body .mdsp-fm tr[data-changed="1"] td:first-child {
box-shadow: inset 3px 0 0 var(--bgColor-success-emphasis, #238636);
}
/* 앞뒤 구분선이 diff 밖이라 일부만 살린 frontmatter — 점선으로 "잘린 표"임을 알린다 */
.mdsp-right .markdown-body .mdsp-fm caption {
caption-side: top; text-align: left; padding: 0 0 4px;
font-size: 11px; color: var(--fgColor-muted, #8b949e);
}
.mdsp-right .markdown-body .mdsp-fm-part table { border-style: dashed; }
/* 접힌 구간 안내 행 — 키 칸 스타일(좁은 폭·굵게)을 물려받지 않게 되돌린다 */
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-gap td,
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-gap td:first-child {
width: auto; white-space: normal; font-weight: 400; text-align: center;
font-size: 11px; color: var(--fgColor-muted, #8b949e); border-right: 0;
}
/* 부모 키가 diff 밖이라 값만 남은 앞머리 */
.mdsp-right .markdown-body .mdsp-fm .mdsp-fm-cut td:first-child { font-weight: 400; }
/* 헤더 줄이 diff 밖이라 표로 파싱되지 않은 구간 — 점선으로 "잘린 표"임을 알린다 */
.mdsp-right .markdown-body .mdsp-table-part { border-collapse: collapse; }
.mdsp-right .markdown-body .mdsp-table-part caption {
caption-side: top; text-align: left; padding: 0 0 4px;
font-size: 11px; color: var(--fgColor-muted, #8b949e);
}
.mdsp-right .markdown-body .mdsp-table-part td {
border: 1px dashed var(--borderColor-default, #30363d);
padding: 5px 12px; vertical-align: top;
/* 열이 좁아져도 "단순" 같은 짧은 말이 글자 단위로 쪼개지지 않게 한다 */
word-break: keep-all;
}
/* 펜스 줄이 diff 밖이라 채워 넣었거나(코드블록) 모양으로 살린(트리) 구간 — 점선으로 알린다 */
.mdsp-right .markdown-body .mdsp-code-part .mdsp-part-note {
padding: 0 0 4px; font-size: 11px; color: var(--fgColor-muted, #8b949e);
}
.mdsp-right .markdown-body .mdsp-code-part pre {
border: 1px dashed var(--borderColor-default, #30363d);
}
/* mermaid 로 그려낸 다이어그램 — 패널이 좁아도 넘치지 않게 가로 스크롤만 준다 */
.mdsp-right .markdown-body .mdsp-mermaid { overflow-x: auto; padding: 4px 0; }
.mdsp-right .markdown-body .mdsp-mermaid svg { max-width: 100%; height: auto; }
/* 문법 오류로 그리지 못해 코드블록으로 되돌린 자리 */
.mdsp-right .markdown-body .mdsp-mermaid-note {
padding: 0 0 4px; font-size: 11px; color: var(--fgColor-danger, #f85149);
}
.mdsp-gap {
display: block;
margin: 14px 0; padding: 3px 0; text-align: center; font-size: 11px;
color: var(--fgColor-muted, #8b949e);
border-top: 1px dashed var(--borderColor-muted, #21262d);
border-bottom: 1px dashed var(--borderColor-muted, #21262d);
}
.mdsp-empty { color: var(--fgColor-muted, #8b949e); font-size: 12px; padding: 8px 0; }
/* markdown-body CSS 가 없는 화면을 위한 최소 폴백 */
.mdsp-right .markdown-body { font-size: 14px; line-height: 1.6; word-wrap: break-word; }
.mdsp-right .markdown-body h1, .mdsp-right .markdown-body h2 {
padding-bottom: .3em; border-bottom: 1px solid var(--borderColor-muted, #21262d);
}
.mdsp-right .markdown-body table { border-collapse: collapse; display: block; overflow-x: auto; max-width: 100%; }
.mdsp-right .markdown-body th, .mdsp-right .markdown-body td {
border: 1px solid var(--borderColor-default, #30363d); padding: 5px 12px;
}
.mdsp-right .markdown-body img { max-width: 100%; }
.mdsp-right .markdown-body pre {
overflow-x: auto; padding: 12px; border-radius: 6px;
background: var(--bgColor-muted, #161b22);
}
.mdsp-right .markdown-body code { font-size: 85%; }
.mdsp-right .markdown-body blockquote {
padding: 0 1em; color: var(--fgColor-muted, #8b949e);
border-left: .25em solid var(--borderColor-default, #30363d);
}
`);
// ─────────────────────────────────────────────── diff DOM → 마크다운 원문 복원
/** 텍스트 셀에서 "변경 후" 라인번호를 얻는다. 여러 GitHub DOM 세대를 순서대로 시도한다. */
function newLineNumber(cell, tr) {
// 1) data-diff-line-key="b:20-l:20-r:20" — r 이 변경 후 라인번호 (현행 React diff)
const key = cell.getAttribute('data-diff-line-key');
if (key) {
const m = /r:(\d+)/.exec(key);
if (m) return parseInt(m[1], 10);
}
// 2) data-line-anchor="diff-<hash>R20" — R = 변경 후
const anchor = cell.getAttribute('data-line-anchor');
if (anchor) {
const m = /R(\d+)$/.exec(anchor);
if (m) return parseInt(m[1], 10);
}
// 3) 같은 행의 right-side 라인번호 셀
const rightNum = tr.querySelector('td[data-diff-side="right"][data-line-number]');
if (rightNum) {
const n = parseInt(rightNum.getAttribute('data-line-number'), 10);
if (Number.isFinite(n)) return n;
}
// 4) data-grid-cell-id="diff-<hash>-<old>-<new>-<col>"
const gid = cell.getAttribute('data-grid-cell-id');
if (gid) {
const p = gid.split('-');
const n = parseInt(p[p.length - 2], 10);
if (Number.isFinite(n)) return n;
}
return null;
}
/** 현행 React diff 에서 변경 후 라인을 추출한다. */
function extractFromReactDiff(scope) {
const rows = scope.querySelectorAll('tr.diff-line-row');
if (!rows.length) return null;
const byLine = new Map();
for (const tr of rows) {
const cells = [...tr.querySelectorAll('td.diff-text-cell')].filter(
(c) => !c.classList.contains('hunk')
);
if (!cells.length) continue;
// unified 는 텍스트 셀이 1개, split 은 2개(좌 old / 우 new) → 항상 마지막이 new 쪽
const cell = cells[cells.length - 1];
const markerEl = cell.querySelector('.diff-text-marker');
const marker = markerEl ? markerEl.textContent.trim() : '';
if (marker === '-') continue; // 삭제 라인은 "변경 후" 에 존재하지 않음
const inner = cell.querySelector('.diff-text-inner');
let text;
if (inner) {
text = inner.textContent;
} else {
const raw = cell.textContent ?? '';
// split 뷰의 빈 자리(placeholder) 셀은 버린다
if (!marker && !raw) continue;
text = marker && raw.startsWith(marker) ? raw.slice(marker.length) : raw;
}
const n = newLineNumber(cell, tr);
if (!Number.isFinite(n)) continue;
const prev = byLine.get(n);
if (prev && !(marker === '+' && !prev.added)) continue;
byLine.set(n, { n, text: text.replace(/\r?\n$/, ''), added: marker === '+' });
}
return [...byLine.values()].sort((a, b) => a.n - b.n);
}
/** 구형 Rails diff(GHE 등) 폴백. */
function extractFromLegacyDiff(scope) {
const markers = scope.querySelectorAll('[data-code-marker]');
if (!markers.length) return null;
const byLine = new Map();
for (const tr of scope.querySelectorAll('tr')) {
const codeTds = [...tr.children].filter(
(td) => td.tagName === 'TD' && td.classList.contains('blob-code')
);
if (!codeTds.length) continue;
const codeTd = codeTds[codeTds.length - 1];
if (codeTd.classList.contains('blob-code-empty') || codeTd.classList.contains('blob-code-hunk')) continue;
const inner = codeTd.querySelector('[data-code-marker]');
if (!inner) continue;
const marker = inner.getAttribute('data-code-marker');
if (marker === '-') continue;
const n = parseInt(codeTd.previousElementSibling?.getAttribute('data-line-number') ?? '', 10);
if (!Number.isFinite(n)) continue;
const prev = byLine.get(n);
if (prev && !(marker === '+' && !prev.added)) continue;
byLine.set(n, { n, text: inner.textContent.replace(/\r?\n$/, ''), added: marker === '+' });
}
return [...byLine.values()].sort((a, b) => a.n - b.n);
}
const extractAfterLines = (scope) =>
extractFromReactDiff(scope) || extractFromLegacyDiff(scope) || [];
// ────────────────────────────────────────────────── 마크다운 렌더링 + 라인 매핑
const escapeHtml = (s) =>
String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
/** GitHub Alert(> [!NOTE] 등)를 GitHub 과 같은 클래스로 바꿔준다. */
function applyAlerts(html) {
return html.replace(
/<blockquote>\s*<p>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(?:<br\s*\/?>)?\s*/gi,
(_m, kind) => {
const k = kind.toLowerCase();
return `<blockquote class="markdown-alert markdown-alert-${k}">` +
`<p class="markdown-alert-title">${k.charAt(0).toUpperCase()}${k.slice(1)}</p><p>`;
}
);
}
/** frontmatter 조각으로 인정할 최대 시작 라인. 이보다 아래에서 시작하면 본문으로 본다. */
const FM_PARTIAL_MAX_LINE = 40;
/** 조각을 frontmatter 로 인정할 최상위 키 꼴. 본문의 `- 항목`·`| 셀` 을 키로 읽지 않게 좁혀 둔다. */
const FM_KEY = /^[A-Za-z0-9_.$-]+$/;
/** 라인들을 접힌 구간 경계로 잘라 "번호가 이어지는 구간" 배열로 만든다. */
function splitSegments(lines) {
const segs = [];
for (const l of lines) {
const cur = segs[segs.length - 1];
if (cur && l.n === cur[cur.length - 1].n + 1) cur.push(l);
else segs.push([l]);
}
return segs;
}
/** 조각 앞머리의 "부모 키가 diff 밖인" 들여쓴 줄·시퀀스 항목을 떼어낸다. */
function splitOrphanHead(seg) {
let i = 0;
while (i < seg.length && (fmIndent(seg[i].text) > 0 || /^-(\s|$)/.test(seg[i].text.trim()))) i++;
return { orphan: seg.slice(0, i), body: seg.slice(i) };
}
/** 조각이 YAML 매핑으로 읽히는가. */
const fmParsable = (seg) => !!parseFrontmatterTree(splitOrphanHead(seg).body);
/**
* 첫 조각 뒤의 조각을 frontmatter 로 이어 볼 수 있는가.
* `looksLikeFrontmatter` 와 같은 근거(빈 줄 없음·키가 YAML 식별자 꼴)를 요구한다.
* 단 부모 키가 diff 밖이라 값만 남은 조각은 읽을 키가 없으므로 그대로 통과시킨다.
*/
function fmSegmentOk(seg) {
if (seg.some((l) => !l.text.trim())) return false;
const body = splitOrphanHead(seg).body;
const rows = parseFrontmatterTree(body);
return rows ? rows.every((r) => FM_KEY.test(r.key)) : !body.length;
}
/** 앞머리 줄들이 YAML 조각처럼 생겼는가(시퀀스 항목이거나 `key: value`). */
const fmOrphanish = (lines) =>
lines.every((l) => {
const t = l.text.trim();
return /^-(\s|$)/.test(t) || !!fmSplitKey(t);
});
/**
* 여는 `---` 가 diff 밖인 조각을 frontmatter 로 인정할지 본다.
* 걸러야 할 것은 `제목: 부제` 뒤에 `---` 가 오는 setext heading 과, 콜론이 섞인 본문이다.
* 빈 줄이 없어야 하고, 키가 모두 YAML 식별자 꼴이어야 하며,
* 그 하나로 끝나지 않는다는 근거(키가 여럿·중첩 값·YAML 앞머리)가 있어야 한다.
*/
function looksLikeFrontmatter(segments) {
if (segments.some((seg) => seg.some((l) => !l.text.trim()))) return false;
const { orphan, body } = splitOrphanHead(segments[0]);
const rows = parseFrontmatterTree(body);
if (!rows || !rows.length) return false;
// 표 조각(`| 항목`)·불릿 목록(`- 생년`)·산문도 `fmSplitKey` 는 키로 통과시킨다.
// 여는 `---` 가 없는 조각은 근거가 이것뿐이므로 키 꼴을 YAML 식별자로 좁힌다
if (!rows.every((r) => FM_KEY.test(r.key))) return false;
return rows.length >= 2 ||
rows.some((r) => r.node && r.node.type !== 'scalar') ||
(orphan.length > 0 && fmOrphanish(orphan));
}
/**
* 파일 맨 앞의 YAML frontmatter 구간을 떼어낸다.
* marked 는 `---` 를 setext heading 으로 읽어 frontmatter 를 거대한 제목으로 만들기 때문에,
* GitHub 처럼 표로 따로 렌더링한다.
*
* frontmatter 를 몇 줄만 고친 PR 은 여는/닫는 `---` 가 diff 밖으로 밀려나므로
* 남은 조각만이라도 표로 살린다. 사이에 접힌 구간이 있으면 조각마다 따로 읽는다.
*/
function extractFrontmatter(lines) {
if (!lines.length) return null;
const opened = lines[0].n === 1 && lines[0].text.trim() === '---';
// 1번 줄이 diff 에 있는데 `---` 가 아니면 이 파일엔 frontmatter 자체가 없다
if (!opened && lines[0].n === 1) return null;
// 여는 `---` 가 없다면 파일 앞부분일 때만 frontmatter 조각으로 본다
if (!opened && lines[0].n > FM_PARTIAL_MAX_LINE) return null;
const segs = splitSegments(opened ? lines.slice(1) : lines);
const segments = [];
let rest = [];
let closed = false;
for (let s = 0; s < segs.length; s++) {
const seg = segs[s];
const at = seg.findIndex((l) => l.text.trim() === '---');
// 닫는 `---` 를 아직 못 봤다면, YAML 로 읽히는 조각까지만 frontmatter 로 본다
if (at === -1 && !fmParsable(seg)) { rest = segs.slice(s).flat(); break; }
const head = at === -1 ? seg : seg.slice(0, at);
// 첫 조각 뒤는 접힌 구간 너머의 본문 hunk 일 수 있다 — 같은 근거를 다시 요구한다
if (s > 0 && head.length && !fmSegmentOk(head)) { rest = segs.slice(s).flat(); break; }
if (head.length) segments.push(head);
if (at !== -1) {
closed = true;
rest = seg.slice(at + 1).concat(segs.slice(s + 1).flat());
break;
}
}
if (!segments.length) return null;
if (!opened && !looksLikeFrontmatter(segments)) return null;
return {
segments,
rest,
startLine: opened ? 1 : segments[0][0].n,
cutHead: !opened,
cutTail: !closed,
};
}
/** frontmatter 본문을 key/value 행으로 만든다. 들여쓴 줄은 직전 키의 값에 이어 붙인다. */
function parseFrontmatterRows(bodyLines) {
const rows = [];
for (const l of bodyLines) {
if (!l.text.trim()) continue;
const m = /^([A-Za-z0-9_.$-]+)\s*:\s*(.*)$/.exec(l.text);
if (m && !/^\s/.test(l.text)) {
rows.push({ key: m[1], value: m[2].trim(), lines: [l] });
} else if (rows.length) {
const last = rows[rows.length - 1];
last.value = last.value ? `${last.value} ${l.text.trim()}` : l.text.trim();
last.lines.push(l);
} else {
rows.push({ key: '', value: l.text.trim(), lines: [l] });
}
}
return rows;
}
// ── frontmatter YAML 파서 ─ 시작 (배열·중첩 객체를 GitHub 처럼 중첩 표로 편다)
const FM_MAX_DEPTH = 8;
/** 선행 공백 폭. 탭이 섞이면 -1 (들여쓰기 폭을 신뢰할 수 없어 파싱을 포기한다). */
function fmIndent(text) {
let i = 0;
while (text[i] === ' ') i++;
return text[i] === '\t' ? -1 : i;
}
/** 따옴표 밖의 ` #` 부터를 주석으로 잘라낸다. */
function fmStripComment(text) {
let quote = null;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (quote) {
if (c === '\\' && quote === '"') i++;
else if (c === quote) quote = null;
} else if (c === '"' || c === "'") quote = c;
else if (c === '#' && (i === 0 || /\s/.test(text[i - 1]))) return text.slice(0, i);
}
return text;
}
/** 따옴표를 벗겨 표시용 문자열로 만든다. */
function fmScalar(raw) {
const t = raw.trim();
if (t.length >= 2 && t[0] === '"' && t[t.length - 1] === '"') {
return t.slice(1, -1).replace(/\\(.)/g, (_m, c) => ({ n: '\n', t: '\t', r: '\r' }[c] ?? c));
}
if (t.length >= 2 && t[0] === "'" && t[t.length - 1] === "'") return t.slice(1, -1).replace(/''/g, "'");
return t;
}
/** `key: value` 를 분해한다. 키 꼴이 아니면 null. */
function fmSplitKey(text) {
let end = -1;
const q = text[0];
if (q === '"' || q === "'") {
for (let i = 1; i < text.length; i++) {
if (text[i] === '\\' && q === '"') { i++; continue; }
if (text[i] === q) { end = i + 1; break; }
}
if (end === -1 || text[end] !== ':') return null;
} else {
// `url: https://x` 처럼 값에 콜론이 있어도 되도록, 뒤가 공백/줄끝인 첫 콜론만 키 구분자로 본다
for (let i = 0; i < text.length; i++) {
if (text[i] === ':' && (i + 1 === text.length || /\s/.test(text[i + 1]))) { end = i; break; }
}
if (end <= 0 || /[[\]{},"']/.test(text.slice(0, end))) return null;
}
return { key: fmScalar(text.slice(0, end)), value: text.slice(end + 1).trim() };
}
/** `[a, b]` / `{k: v}` 같은 flow 표기를 노드로 만든다. 형식이 아니면 null. */
function fmParseFlow(src) {
if (src[0] !== '[' && src[0] !== '{') return null;
let p = 0;
const ws = () => { while (p < src.length && /\s/.test(src[p])) p++; };
const token = (stopColon) => {
const start = p;
let quote = null;
while (p < src.length) {
const c = src[p];
if (quote) {
if (c === '\\' && quote === '"') p++;
else if (c === quote) quote = null;
} else if ('[]{},'.includes(c) || (stopColon && c === ':')) break;
else if (c === '"' || c === "'") quote = c;
p++;
}
if (p === start) throw new Error('flow');
return src.slice(start, p);
};
const value = (depth) => {
if (depth > FM_MAX_DEPTH) throw new Error('deep');
ws();
if (src[p] === '[') { p++; return collection(depth, ']'); }
if (src[p] === '{') { p++; return collection(depth, '}'); }
return { type: 'scalar', text: fmScalar(token(false)) };
};
const collection = (depth, close) => {
const isMap = close === '}';
const items = [];
const entries = [];
const done = () => (isMap ? { type: 'map', entries } : { type: 'seq', items });
ws();
if (src[p] === close) { p++; return done(); }
for (;;) {
if (isMap) {
ws();
const key = token(true);
ws();
if (src[p] !== ':') throw new Error('flow');
p++;
entries.push({ key: fmScalar(key), node: value(depth + 1) });
} else {
items.push(value(depth + 1));
}
ws();
if (src[p] === ',') { p++; ws(); if (src[p] !== close) continue; }
if (src[p] !== close) throw new Error('flow');
p++;
return done();
}
};
try {
const node = value(0);
ws();
return p === src.length ? node : null;
} catch { return null; }
}
/**
* frontmatter 본문을 트리로 파싱한다. 최상위 키마다 { key, node, lines } 를 돌려준다.
* 지원: 블록 매핑/시퀀스, flow 표기, 따옴표·블록(`|` `>`) 스칼라, 주석.
* 지원 밖 문법을 만나면 null 을 돌려 호출부가 예전의 단순 key/value 표로 폴백하게 한다.
*/
function parseFrontmatterTree(bodyLines) {
const src = bodyLines.map((l) => ({
indent: fmIndent(l.text), text: fmStripComment(l.text).trim(), raw: l.text,
}));
if (src.some((s) => s.indent < 0)) return null;
let i = 0;
const skipBlank = () => { while (i < src.length && !src[i].text) i++; };
function parseValue(indent, depth) {
if (depth > FM_MAX_DEPTH) throw new Error('deep');
skipBlank();
if (i >= src.length || src[i].indent < indent) return { type: 'scalar', text: '' };
return /^-(\s|$)/.test(src[i].text) ? parseSeq(src[i].indent, depth) : parseMap(src[i].indent, depth);
}
function parseMap(indent, depth) {
const entries = [];
for (;;) {
skipBlank();
if (i >= src.length || src[i].indent < indent) break;
if (src[i].indent > indent) throw new Error('indent');
const kv = fmSplitKey(src[i].text);
if (!kv) throw new Error('key');
const from = i;
i++;
const node = parseAfterKey(kv.value, indent, depth);
entries.push({ key: kv.key, node, from, to: i });
}
if (!entries.length) throw new Error('empty');
return { type: 'map', entries };
}
function parseAfterKey(value, indent, depth) {
if (/^[|>][+-]?\d*$/.test(value)) return parseBlockScalar(value[0] === '>', indent);
if (value) return fmParseFlow(value) || { type: 'scalar', text: fmScalar(value) };
// 값이 다음 줄부터인 경우
skipBlank();
if (i >= src.length) return { type: 'scalar', text: '' };
if (src[i].indent > indent) return parseValue(src[i].indent, depth + 1);
// 시퀀스는 부모 키와 같은 깊이로 쓰는 표기도 흔하다
if (src[i].indent === indent && /^-(\s|$)/.test(src[i].text)) return parseSeq(indent, depth + 1);
return { type: 'scalar', text: '' };
}
function parseBlockScalar(fold, indent) {
const buf = [];
let base = null;
while (i < src.length) {
const raw = src[i].raw;
if (!raw.trim()) { buf.push(''); i++; continue; } // 블록 스칼라 안에서는 주석도 내용이다
if (fmIndent(raw) <= indent) break;
if (base === null) base = fmIndent(raw);
buf.push(raw.slice(base));
i++;
}
while (buf.length && !buf[buf.length - 1]) buf.pop();
return { type: 'scalar', text: fold ? buf.join(' ').trim() : buf.join('\n') };
}
function parseSeq(indent, depth) {
const items = [];
for (;;) {
skipBlank();
if (i >= src.length) break;
const cur = src[i];
if (cur.indent !== indent || !/^-(\s|$)/.test(cur.text)) break;
const rest = cur.text.slice(1).trim();
if (!rest) {
i++;
skipBlank();
items.push(i < src.length && src[i].indent > indent
? parseValue(src[i].indent, depth + 1)
: { type: 'scalar', text: '' });
continue;
}
if (fmSplitKey(rest)) {
// `- key: value` 컴팩트 매핑 — 대시 뒤 컬럼을 그 매핑의 들여쓰기로 삼아 다음 줄들과 이어 읽는다
const off = cur.text.indexOf(rest, 1);
src[i] = { indent: indent + off, text: rest, raw: cur.raw };
items.push(parseMap(indent + off, depth + 1));
continue;
}
i++;
items.push(fmParseFlow(rest) || { type: 'scalar', text: fmScalar(rest) });
}
if (!items.length) throw new Error('empty');
return { type: 'seq', items };
}
try {
skipBlank();
if (i >= src.length || src[i].indent !== 0) return null;
const root = parseMap(0, 0);
if (i < src.length) return null; // 다 읽지 못했으면 해석이 어긋난 것이다
return root.entries.map((e) => ({ key: e.key, node: e.node, lines: bodyLines.slice(e.from, e.to) }));
} catch { return null; }
}
/** 값 노드를 표로 렌더링한다. 시퀀스는 한 줄로, 매핑은 키 행 + 값 행으로 편다(GitHub 과 동일). */
function renderFmValue(node) {
if (!node) return '';
if (node.type === 'scalar') return escapeHtml(node.text).replace(/\n/g, '<br>');
if (node.type === 'seq') {
if (!node.items.length) return '';
return '<table class="mdsp-fm-sub"><tbody><tr>' +
node.items.map((v) => `<td>${renderFmValue(v)}</td>`).join('') +
'</tr></tbody></table>';
}
if (!node.entries.length) return '';
return '<table class="mdsp-fm-sub"><tbody>' +
`<tr>${node.entries.map((e) => `<th>${escapeHtml(e.key)}</th>`).join('')}</tr>` +
`<tr>${node.entries.map((e) => `<td>${renderFmValue(e.node)}</td>`).join('')}</tr>` +
'</tbody></table>';
}
// ── frontmatter YAML 파서 ─ 끝
const FM_GAP_ROW =
'<tr class="mdsp-fm-gap"><td colspan="2">⋯ 접힌 구간 (왼쪽 diff에서 펼치면 반영됩니다) ⋯</td></tr>';
/** 표 한 행. 추가된 줄이 섞여 있으면 초록으로 강조한다. */
function fmRow(key, value, lines, cls) {
const changed = lines.some((l) => l.added);
return `<tr${cls ? ` class="${cls}"` : ''}${changed ? ' data-changed="1"' : ''}>` +
`<td>${key}</td><td>${value}</td></tr>`;
}
/** 조각 하나를 표 행들로 만든다. 부모 키가 diff 밖인 앞머리는 값만 한 행에 모아 둔다. */
function renderFmSegment(seg) {
const { orphan, body } = splitOrphanHead(seg);
const rows = parseFrontmatterTree(body) ||
parseFrontmatterRows(body).map((r) => ({ key: r.key, node: { type: 'scalar', text: r.value }, lines: r.lines }));
const out = [];
if (orphan.length) {
const text = orphan.map((l) => escapeHtml(l.text.trim())).join('<br>');
out.push(fmRow('⋯', text, orphan, 'mdsp-fm-cut'));
}
for (const r of rows) out.push(fmRow(escapeHtml(r.key), renderFmValue(r.node), r.lines));
return out.join('');
}
function renderFrontmatter(fm) {
const body = fm.segments.map(renderFmSegment).filter(Boolean).join(FM_GAP_ROW);
if (!body) return '';
const where = fm.cutHead && fm.cutTail ? '앞뒤' : (fm.cutHead ? '시작' : '끝');
const partial = fm.cutHead || fm.cutTail;
const caption = partial
? `<caption>frontmatter 일부 · ${where} 부분이 diff 밖에 있습니다 (왼쪽에서 펼치면 전체로 보입니다)</caption>`
: '';
return `<div class="mdsp-block mdsp-fm${partial ? ' mdsp-fm-part' : ''}" data-line="${fm.startLine}">` +
`<table>${caption}<tbody>${body}</tbody></table></div>`;
}
// ── 표 조각 렌더 ─ 시작
/** `| a | b |` 처럼 파이프로 감싼 표 행. */
const TABLE_ROW = /^\s*\|.*\|\s*$/;
/** `|---|:--:|` 같은 헤더 구분선. */
const TABLE_DELIM = /^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-*:?\s*\|?\s*$/;
/** 표 행 한 줄을 셀로 나눈다. `\|` 는 셀 안의 리터럴 파이프다. */
function splitTableRow(line) {
const t = line.trim().replace(/^\|/, '').replace(/\|$/, '');
const cells = [];
let cur = '';
for (let i = 0; i < t.length; i++) {
const c = t[i];
if (c === '\\' && t[i + 1] === '|') { cur += '|'; i++; continue; }
if (c === '|') { cells.push(cur); cur = ''; continue; }
cur += c;
}
cells.push(cur);
return cells.map((s) => s.trim());
}
/**
* 표 한가운데 몇 줄만 diff 에 들어오면 헤더 줄과 구분선이 빠져 있어
* marked 가 문단으로 읽고 `| 셀 | 셀 |` 이 그대로 노출된다.
* 그런 구간을 찾아 셀로 되돌린다. 표 조각이 아니면 null.
*/
function parseTableFragment(raw) {
const lines = raw.replace(/\s+$/, '').split('\n').filter((l) => l.trim());
if (!lines.length || !lines.every((l) => TABLE_ROW.test(l))) return null;
const rows = [];
for (const l of lines) {
if (TABLE_DELIM.test(l)) continue; // 헤더는 접히고 구분선만 남은 경우
const cells = splitTableRow(l);
if (cells.length < 2) return null; // 셀이 하나뿐이면 표로 보기 어렵다
rows.push(cells);
}
return rows.length ? rows : null;
}
/** 표 조각을 헤더 없는 표로 렌더링한다. 잘린 구간임을 캡션과 점선으로 알린다. */
function renderTableFragment(rows) {
const width = rows.reduce((max, r) => Math.max(max, r.length), 0);
const body = rows
.map((cells) => {
let tds = '';
for (let i = 0; i < width; i++) {
const src = cells[i] ?? '';
let cell;
try { cell = MD.parseInline(src); } catch { cell = escapeHtml(src); }
tds += `<td>${cell}</td>`;
}
return `<tr>${tds}</tr>`;
})
.join('');
return '<table class="mdsp-table-part">' +
'<caption>표 일부 · 헤더 줄이 diff 밖에 있습니다 (왼쪽에서 펼치면 표 전체로 보입니다)</caption>' +
`<tbody>${body}</tbody></table>`;
}
// ── 표 조각 렌더 ─ 끝
// ── 트리 조각 렌더 ─ 시작
/** `├──` `└──` `│` 처럼 박스 드로잉으로 시작하는 줄 — `tree` 출력의 가지. */
const TREE_BRANCH = /^[ \t]*[\u2500-\u257F]/;
/** 트리 맨 윗줄에 올 수 있는 루트 — `flows/` 처럼 공백 없는 한 덩어리(뒤 주석은 허용). */
const TREE_ROOT = /^[ \t]*[^\s#][^\s]*[ \t]*(#.*)?$/;
/**
* 코드블록 안 디렉터리 트리는 몇 줄만 고쳐도 여는 ``` 과 닫는 ``` 이 함께
* diff 밖으로 밀려난다. 조각에 펜스가 한 줄도 없으니 balanceFences 가 채울
* 근거가 없고, marked 는 문단으로 읽어 줄바꿈과 칸 맞춤을 통째로 무너뜨린다.
*
* 가지 문자로 시작하는 줄이 둘 이상인 구간만 트리로 보고 원문을 그대로 돌려준다.
* 트리가 아니면 null.
*/
function parseTreeFragment(raw) {
const text = raw.replace(/\s+$/, '');
const lines = text.split('\n').filter((l) => l.trim());
if (lines.length < 2) return null; // 한 줄은 문단으로 붙어도 잃는 게 없다
const branches = lines.filter((l) => TREE_BRANCH.test(l)).length;
if (branches < 2) return null; // 본문에 섞인 가로줄 한 줄은 트리가 아니다
if (branches === lines.length) return text;
// 가지가 아닌 줄은 맨 위 루트 한 줄까지만 봐준다
const root = lines[0];
return branches === lines.length - 1 && !TREE_BRANCH.test(root) && TREE_ROOT.test(root)
? text
: null;
}
/**
* 트리 조각을 줄바꿈·칸 맞춤 그대로 보여준다.
* 펜스를 눈으로 확인한 게 아니라 모양으로 짐작한 자리라, 안내도 본 것만 적는다.
*/
function renderTreeFragment(text) {
const note =
'<div class="mdsp-part-note">트리 구조 · diff 안에 <code>```</code> 이 없어 ' +
'원문 줄바꿈을 살려서 보여줍니다 (왼쪽에서 펼치면 전체로 보입니다)</div>';
return `<div class="mdsp-code-part">${note}<pre><code>${escapeHtml(text)}</code></pre></div>`;
}
// ── 트리 조각 렌더 ─ 끝
// ── 잘린 코드펜스 보정 ─ 시작
/** 코드펜스 한 줄이면 marker 와 컨테이너 prefix 를, 아니면 null 을 돌려준다. */
function fenceLine(text) {
let rest = text;
let quotePrefix = '';
let quoteDepth = 0;
for (;;) {
const q = /^ {0,3}>[ \t]?/.exec(rest);
if (!q) break;
quotePrefix += q[0];
rest = rest.slice(q[0].length);
quoteDepth++;
}
const m = /^( *)((?:`{3,})|(?:~{3,}))(.*)$/.exec(rest);
if (!m) return null;
const info = m[3].trim();
// 백틱 펜스의 info string 에는 백틱이 들어갈 수 없다 (CommonMark)
if (m[2][0] === '`' && info.includes('`')) return null;
return {
marker: m[2], info, quoteDepth, indent: m[1].length,
prefix: quotePrefix + m[1],
};
}
/** blockquote marker 를 걷어낸 뒤의 내용과 깊이. */
function quoteLine(text) {
let rest = text;
let depth = 0;
for (;;) {
const q = /^ {0,3}>[ \t]?/.exec(rest);
if (!q) break;
rest = rest.slice(q[0].length);
depth++;
}
return { depth, rest };
}
const GAP_LABEL = '⋯ 접힌 구간 (왼쪽 diff에서 펼치면 반영됩니다) ⋯';
/** fence 가 속한 blockquote/list gap만 raw span으로 바꿔 컨테이너를 보존한다. */
function preserveQuoteGaps(srcLines, lineNoOf, eligible) {
const inlineGapAfter = new Set();
for (const i of eligible) {
if (i < 1 || i >= srcLines.length - 1) continue;
if (lineNoOf[i] != null || lineNoOf[i - 1] == null || lineNoOf[i + 1] == null) continue;
const before = quoteLine(srcLines[i - 1]);
const after = quoteLine(srcLines[i + 1]);
if (!before.depth || before.depth !== after.depth) continue;
const quotePrefix = `${Array(before.depth).fill('>').join(' ')} `;
const indent = /^ */.exec(after.rest)[0];
srcLines[i] = quotePrefix + indent + `<span class="mdsp-gap">${GAP_LABEL}</span>`;
inlineGapAfter.add(lineNoOf[i - 1]);
}
return inlineGapAfter;
}
/** fence 를 감싸는 가장 가까운 목록 marker 와 content 들여쓰기를 찾는다. */
function findListContext(srcLines, lineNoOf, at, fence) {
if (!fence.indent) return null;
for (let i = at - 1; i >= 0; i--) {
if (lineNoOf[i] == null) continue;
const line = quoteLine(srcLines[i]);
if (line.depth !== fence.quoteDepth) return null;
if (!line.rest.trim()) continue;
const indent = /^ */.exec(line.rest)[0].length;
const list = /^( *)([-+*]|\d{1,9}[.)])( {1,4})/.exec(line.rest);
if (list) {
const contentIndent = list[1].length + list[2].length + list[3].length;
const relative = fence.indent - contentIndent;
if (relative >= 0 && relative <= 3) return { at: i, contentIndent };
}
if (indent === 0) return null;
}
return null;
}
function closesFence(open, fence) {
return fence && !fence.info &&
fence.context === open.context &&
fence.marker[0] === open.marker[0] &&
fence.marker.length >= open.marker.length;
}
/** 주어진 시작 상태로 scope 를 읽고 changed line 이 코드 안에 드는 정도를 센다. */
function scoreFenceRun(scope, fences, lineNoOf, changedLines, initial) {
const fenceAt = new Map(fences.map((f) => [f.i, f]));
let open = initial ? { ...initial } : null;
let inside = 0;
let outside = 0;
const codeLines = new Set();
for (let i = scope.start; i <= scope.end; i++) {
const fence = fenceAt.get(i);
const changed = changedLines.has(lineNoOf[i]);
if (open) {
codeLines.add(i);
if (changed) inside++;
if (closesFence(open, fence)) open = null;
} else if (fence) {
open = { ...fence };
codeLines.add(i);
if (changed) inside++;
} else if (changed) {
outside++;
}
}
return { initial, open, score: inside * 2 - outside, codeLines };
}
/**
* diff 조각에는 코드펜스의 한쪽만 들어오는 일이 잦다.
* 닫는 ``` 만 들어오면 marked 가 그걸 여는 펜스로 읽어 뒤따르는 문서 전체를
* 코드블록으로 삼켜버린다 (인용문·목록이 원문 그대로 노출된다).