tedi 0.16.3

Personal productivity CLI for task tracking, time management, and GitHub issue integration
Documentation
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
//! Owned markdown event types for storage.
//!
//! This module provides owned versions of pulldown_cmark events that can be stored
//! in data structures without lifetime concerns. Events are parsed using pulldown_cmark
//! and rendered back to markdown on demand.

use std::fmt;

use pulldown_cmark::{Alignment, BlockQuoteKind, CodeBlockKind, Event, HeadingLevel, LinkType, MetadataBlockKind, Tag, TagEnd};

/// An owned markdown event that can be stored without lifetimes.
/// This is the internal representation - we parse markdown into these and render back on demand.
#[derive(Clone, Debug, PartialEq)]
pub enum OwnedEvent {
	Start(OwnedTag),
	End(OwnedTagEnd),
	Text(String),
	Code(String),
	InlineHtml(String),
	Html(String),
	InlineMath(String),
	DisplayMath(String),
	FootnoteReference(String),
	SoftBreak,
	HardBreak,
	Rule,
	/// Checkbox: raw contents between `[` and `]`.
	/// Standard: `" "` (unchecked), `"x"` (checked).
	/// Custom: anything else (e.g. `"."` for partial).
	CheckBox(String),
}

impl OwnedEvent {
	/// Convert from a pulldown_cmark Event (borrowing the data).
	pub fn from_event(event: Event<'_>) -> Self {
		match event {
			Event::Start(tag) => OwnedEvent::Start(OwnedTag::from_tag(tag)),
			Event::End(tag_end) => OwnedEvent::End(OwnedTagEnd::from_tag_end(tag_end)),
			Event::Text(text) => OwnedEvent::Text(text.into_string()),
			Event::Code(code) => OwnedEvent::Code(code.into_string()),
			Event::InlineHtml(html) => OwnedEvent::InlineHtml(html.into_string()),
			Event::Html(html) => OwnedEvent::Html(html.into_string()),
			Event::InlineMath(math) => OwnedEvent::InlineMath(math.into_string()),
			Event::DisplayMath(math) => OwnedEvent::DisplayMath(math.into_string()),
			Event::FootnoteReference(name) => OwnedEvent::FootnoteReference(name.into_string()),
			Event::SoftBreak => OwnedEvent::SoftBreak,
			Event::HardBreak => OwnedEvent::HardBreak,
			Event::Rule => OwnedEvent::Rule,
			Event::TaskListMarker(checked) => OwnedEvent::CheckBox(if checked { "x" } else { " " }.into()),
		}
	}

	/// Convert back to a pulldown_cmark Event (borrowing from self).
	pub fn to_event(&self) -> Event<'_> {
		match self {
			OwnedEvent::Start(tag) => Event::Start(tag.to_tag()),
			OwnedEvent::End(tag_end) => Event::End(tag_end.to_tag_end()),
			OwnedEvent::Text(text) => Event::Text(text.as_str().into()),
			OwnedEvent::Code(code) => Event::Code(code.as_str().into()),
			OwnedEvent::InlineHtml(html) => Event::InlineHtml(html.as_str().into()),
			OwnedEvent::Html(html) => Event::Html(html.as_str().into()),
			OwnedEvent::InlineMath(math) => Event::InlineMath(math.as_str().into()),
			OwnedEvent::DisplayMath(math) => Event::DisplayMath(math.as_str().into()),
			OwnedEvent::FootnoteReference(name) => Event::FootnoteReference(name.as_str().into()),
			OwnedEvent::SoftBreak => Event::SoftBreak,
			OwnedEvent::HardBreak => Event::HardBreak,
			OwnedEvent::Rule => Event::Rule,
			OwnedEvent::CheckBox(inner) => match inner.as_str() {
				" " => Event::TaskListMarker(false),
				"x" => Event::TaskListMarker(true),
				_ => panic!("CheckBox(\"{inner}\") cannot be converted to Event directly; use prepare_for_render()"),
			},
		}
	}
}

/// An owned tag for Start events.
#[derive(Clone, Debug, PartialEq)]
pub enum OwnedTag {
	Paragraph,
	Heading {
		level: HeadingLevel,
		id: Option<String>,
		classes: Vec<String>,
		attrs: Vec<(String, Option<String>)>,
	},
	BlockQuote(Option<BlockQuoteKind>),
	CodeBlock(OwnedCodeBlockKind),
	HtmlBlock,
	List(Option<u64>),
	Item,
	FootnoteDefinition(String),
	DefinitionList,
	DefinitionListTitle,
	DefinitionListDefinition,
	Table(Vec<Alignment>),
	TableHead,
	TableRow,
	TableCell,
	Emphasis,
	Strong,
	Strikethrough,
	Link {
		link_type: LinkType,
		dest_url: String,
		title: String,
		id: String,
	},
	Image {
		link_type: LinkType,
		dest_url: String,
		title: String,
		id: String,
	},
	MetadataBlock(MetadataBlockKind),
	Superscript,
	Subscript,
}

impl OwnedTag {
	pub fn from_tag(tag: Tag<'_>) -> Self {
		match tag {
			Tag::Paragraph => OwnedTag::Paragraph,
			Tag::Heading { level, id, classes, attrs } => OwnedTag::Heading {
				level,
				id: id.map(|s| s.into_string()),
				classes: classes.into_iter().map(|s| s.into_string()).collect(),
				attrs: attrs.into_iter().map(|(k, v)| (k.into_string(), v.map(|s| s.into_string()))).collect(),
			},
			Tag::BlockQuote(kind) => OwnedTag::BlockQuote(kind),
			Tag::CodeBlock(kind) => OwnedTag::CodeBlock(OwnedCodeBlockKind::from_kind(kind)),
			Tag::HtmlBlock => OwnedTag::HtmlBlock,
			Tag::List(start) => OwnedTag::List(start),
			Tag::Item => OwnedTag::Item,
			Tag::FootnoteDefinition(name) => OwnedTag::FootnoteDefinition(name.into_string()),
			Tag::DefinitionList => OwnedTag::DefinitionList,
			Tag::DefinitionListTitle => OwnedTag::DefinitionListTitle,
			Tag::DefinitionListDefinition => OwnedTag::DefinitionListDefinition,
			Tag::Table(alignments) => OwnedTag::Table(alignments),
			Tag::TableHead => OwnedTag::TableHead,
			Tag::TableRow => OwnedTag::TableRow,
			Tag::TableCell => OwnedTag::TableCell,
			Tag::Emphasis => OwnedTag::Emphasis,
			Tag::Strong => OwnedTag::Strong,
			Tag::Strikethrough => OwnedTag::Strikethrough,
			Tag::Link { link_type, dest_url, title, id } => OwnedTag::Link {
				link_type,
				dest_url: dest_url.into_string(),
				title: title.into_string(),
				id: id.into_string(),
			},
			Tag::Image { link_type, dest_url, title, id } => OwnedTag::Image {
				link_type,
				dest_url: dest_url.into_string(),
				title: title.into_string(),
				id: id.into_string(),
			},
			Tag::MetadataBlock(kind) => OwnedTag::MetadataBlock(kind),
			Tag::Superscript => OwnedTag::Superscript,
			Tag::Subscript => OwnedTag::Subscript,
		}
	}

	pub fn to_tag(&self) -> Tag<'_> {
		match self {
			OwnedTag::Paragraph => Tag::Paragraph,
			OwnedTag::Heading { level, id, classes, attrs } => Tag::Heading {
				level: *level,
				id: id.as_deref().map(Into::into),
				classes: classes.iter().map(|s| s.as_str().into()).collect(),
				attrs: attrs.iter().map(|(k, v)| (k.as_str().into(), v.as_deref().map(Into::into))).collect(),
			},
			OwnedTag::BlockQuote(kind) => Tag::BlockQuote(*kind),
			OwnedTag::CodeBlock(kind) => Tag::CodeBlock(kind.to_kind()),
			OwnedTag::HtmlBlock => Tag::HtmlBlock,
			OwnedTag::List(start) => Tag::List(*start),
			OwnedTag::Item => Tag::Item,
			OwnedTag::FootnoteDefinition(name) => Tag::FootnoteDefinition(name.as_str().into()),
			OwnedTag::DefinitionList => Tag::DefinitionList,
			OwnedTag::DefinitionListTitle => Tag::DefinitionListTitle,
			OwnedTag::DefinitionListDefinition => Tag::DefinitionListDefinition,
			OwnedTag::Table(alignments) => Tag::Table(alignments.clone()),
			OwnedTag::TableHead => Tag::TableHead,
			OwnedTag::TableRow => Tag::TableRow,
			OwnedTag::TableCell => Tag::TableCell,
			OwnedTag::Emphasis => Tag::Emphasis,
			OwnedTag::Strong => Tag::Strong,
			OwnedTag::Strikethrough => Tag::Strikethrough,
			OwnedTag::Link { link_type, dest_url, title, id } => Tag::Link {
				link_type: *link_type,
				dest_url: dest_url.as_str().into(),
				title: title.as_str().into(),
				id: id.as_str().into(),
			},
			OwnedTag::Image { link_type, dest_url, title, id } => Tag::Image {
				link_type: *link_type,
				dest_url: dest_url.as_str().into(),
				title: title.as_str().into(),
				id: id.as_str().into(),
			},
			OwnedTag::MetadataBlock(kind) => Tag::MetadataBlock(*kind),
			OwnedTag::Superscript => Tag::Superscript,
			OwnedTag::Subscript => Tag::Subscript,
		}
	}
}

/// An owned tag end for End events.
#[derive(Clone, Debug, PartialEq)]
pub enum OwnedTagEnd {
	Paragraph,
	Heading(HeadingLevel),
	BlockQuote(Option<BlockQuoteKind>),
	CodeBlock,
	HtmlBlock,
	List(bool),
	Item,
	FootnoteDefinition,
	DefinitionList,
	DefinitionListTitle,
	DefinitionListDefinition,
	Table,
	TableHead,
	TableRow,
	TableCell,
	Emphasis,
	Strong,
	Strikethrough,
	Link,
	Image,
	MetadataBlock(MetadataBlockKind),
	Superscript,
	Subscript,
}

impl OwnedTagEnd {
	pub fn from_tag_end(tag_end: TagEnd) -> Self {
		match tag_end {
			TagEnd::Paragraph => OwnedTagEnd::Paragraph,
			TagEnd::Heading(level) => OwnedTagEnd::Heading(level),
			TagEnd::BlockQuote(kind) => OwnedTagEnd::BlockQuote(kind),
			TagEnd::CodeBlock => OwnedTagEnd::CodeBlock,
			TagEnd::HtmlBlock => OwnedTagEnd::HtmlBlock,
			TagEnd::List(ordered) => OwnedTagEnd::List(ordered),
			TagEnd::Item => OwnedTagEnd::Item,
			TagEnd::FootnoteDefinition => OwnedTagEnd::FootnoteDefinition,
			TagEnd::DefinitionList => OwnedTagEnd::DefinitionList,
			TagEnd::DefinitionListTitle => OwnedTagEnd::DefinitionListTitle,
			TagEnd::DefinitionListDefinition => OwnedTagEnd::DefinitionListDefinition,
			TagEnd::Table => OwnedTagEnd::Table,
			TagEnd::TableHead => OwnedTagEnd::TableHead,
			TagEnd::TableRow => OwnedTagEnd::TableRow,
			TagEnd::TableCell => OwnedTagEnd::TableCell,
			TagEnd::Emphasis => OwnedTagEnd::Emphasis,
			TagEnd::Strong => OwnedTagEnd::Strong,
			TagEnd::Strikethrough => OwnedTagEnd::Strikethrough,
			TagEnd::Link => OwnedTagEnd::Link,
			TagEnd::Image => OwnedTagEnd::Image,
			TagEnd::MetadataBlock(kind) => OwnedTagEnd::MetadataBlock(kind),
			TagEnd::Superscript => OwnedTagEnd::Superscript,
			TagEnd::Subscript => OwnedTagEnd::Subscript,
		}
	}

	pub fn to_tag_end(&self) -> TagEnd {
		match self {
			OwnedTagEnd::Paragraph => TagEnd::Paragraph,
			OwnedTagEnd::Heading(level) => TagEnd::Heading(*level),
			OwnedTagEnd::BlockQuote(kind) => TagEnd::BlockQuote(*kind),
			OwnedTagEnd::CodeBlock => TagEnd::CodeBlock,
			OwnedTagEnd::HtmlBlock => TagEnd::HtmlBlock,
			OwnedTagEnd::List(ordered) => TagEnd::List(*ordered),
			OwnedTagEnd::Item => TagEnd::Item,
			OwnedTagEnd::FootnoteDefinition => TagEnd::FootnoteDefinition,
			OwnedTagEnd::DefinitionList => TagEnd::DefinitionList,
			OwnedTagEnd::DefinitionListTitle => TagEnd::DefinitionListTitle,
			OwnedTagEnd::DefinitionListDefinition => TagEnd::DefinitionListDefinition,
			OwnedTagEnd::Table => TagEnd::Table,
			OwnedTagEnd::TableHead => TagEnd::TableHead,
			OwnedTagEnd::TableRow => TagEnd::TableRow,
			OwnedTagEnd::TableCell => TagEnd::TableCell,
			OwnedTagEnd::Emphasis => TagEnd::Emphasis,
			OwnedTagEnd::Strong => TagEnd::Strong,
			OwnedTagEnd::Strikethrough => TagEnd::Strikethrough,
			OwnedTagEnd::Link => TagEnd::Link,
			OwnedTagEnd::Image => TagEnd::Image,
			OwnedTagEnd::MetadataBlock(kind) => TagEnd::MetadataBlock(*kind),
			OwnedTagEnd::Superscript => TagEnd::Superscript,
			OwnedTagEnd::Subscript => TagEnd::Subscript,
		}
	}
}

/// An owned code block kind.
#[derive(Clone, Debug, PartialEq)]
pub enum OwnedCodeBlockKind {
	Indented,
	Fenced(String),
}

impl OwnedCodeBlockKind {
	pub fn from_kind(kind: CodeBlockKind<'_>) -> Self {
		match kind {
			CodeBlockKind::Indented => OwnedCodeBlockKind::Indented,
			CodeBlockKind::Fenced(info) => OwnedCodeBlockKind::Fenced(info.into_string()),
		}
	}

	pub fn to_kind(&self) -> CodeBlockKind<'_> {
		match self {
			OwnedCodeBlockKind::Indented => CodeBlockKind::Indented,
			OwnedCodeBlockKind::Fenced(info) => CodeBlockKind::Fenced(info.as_str().into()),
		}
	}
}

/// A sequence of owned markdown events.
/// This is the primary type for storing markdown content.
#[derive(Clone, Debug, Default, derive_more::Deref, derive_more::IntoIterator, PartialEq)]
pub struct Events(Vec<OwnedEvent>);
impl Events {
	/// Parse markdown content into events.
	///
	/// Handles checkbox coercion inline: pulldown_cmark turns `\[.\]` into
	/// `Text("[.")` + `Text("] rest")` — we detect this pattern inside list items
	/// and replace with `CheckBox(inner)` + optional `Text(rest)`.
	pub fn parse(content: &str) -> Self {
		use pulldown_cmark::Parser;
		let parser = Parser::new_ext(content, parser_options());
		let raw: Vec<OwnedEvent> = parser.map(OwnedEvent::from_event).collect();

		// Single pass: detect escaped-checkbox patterns and coerce them.
		// After Start(Item) [+ optional Start(Paragraph)], detect:
		//   2-event: Text("[<inner>") + Text("] <rest>")
		//   4-event: Text("[") + Text(<inner>) + Text("]") + Text(" <rest>")
		// Replace with CheckBox(inner) + optional Text(rest).
		let mut events = Vec::with_capacity(raw.len());
		let mut i = 0;
		while i < raw.len() {
			if !matches!(&raw[i], OwnedEvent::Start(OwnedTag::Item)) {
				events.push(raw[i].clone());
				i += 1;
				continue;
			}
			// Push Start(Item)
			events.push(raw[i].clone());
			i += 1;

			// Skip optional Start(Paragraph)
			let had_paragraph = i < raw.len() && matches!(&raw[i], OwnedEvent::Start(OwnedTag::Paragraph));
			if had_paragraph {
				events.push(raw[i].clone());
				i += 1;
			}

			// Already a CheckBox (from TaskListMarker) — skip coercion
			if i < raw.len() && matches!(&raw[i], OwnedEvent::CheckBox(_)) {
				continue;
			}

			// Try 4-event pattern: Text("[") + Text(<inner>) + Text("]") + Text(" <rest>")
			if i + 3 < raw.len()
				&& let (OwnedEvent::Text(open), OwnedEvent::Text(inner), OwnedEvent::Text(close), OwnedEvent::Text(rest)) = (&raw[i], &raw[i + 1], &raw[i + 2], &raw[i + 3])
				&& open == "["
				&& close == "]"
				&& (rest.is_empty() || rest.starts_with(' '))
			{
				events.push(OwnedEvent::CheckBox(inner.clone()));
				let rest = rest.strip_prefix(' ').unwrap_or(rest);
				if !rest.is_empty() {
					events.push(OwnedEvent::Text(rest.to_string()));
				}
				i += 4;
				continue;
			}

			// Try 3-event patterns (two variants from partial escaping):
			//   A: Text("[") + Text(<inner>) + Text("] <rest>")   — \[ escaped, \] joins with rest
			//   B: Text("[<inner>") + Text("]") + Text(" <rest>") — \[ joins with inner, ] separate
			if i + 2 < raw.len() {
				let (a, b, c) = (&raw[i], &raw[i + 1], &raw[i + 2]);
				let matched = if let (OwnedEvent::Text(open), OwnedEvent::Text(inner), OwnedEvent::Text(rest)) = (a, b, c)
					&& open == "[" && let Some(rest) = rest.strip_prefix(']')
					&& (rest.is_empty() || rest.starts_with(' '))
				{
					Some((inner.clone(), rest.strip_prefix(' ').unwrap_or(rest).to_string()))
				} else if let (OwnedEvent::Text(first), OwnedEvent::Text(close), OwnedEvent::Text(rest)) = (a, b, c)
					&& let Some(inner) = first.strip_prefix('[')
					&& close == "]" && (rest.is_empty() || rest.starts_with(' '))
				{
					Some((inner.to_string(), rest.strip_prefix(' ').unwrap_or(rest).to_string()))
				} else {
					None
				};
				if let Some((inner, rest)) = matched {
					events.push(OwnedEvent::CheckBox(inner));
					if !rest.is_empty() {
						events.push(OwnedEvent::Text(rest));
					}
					i += 3;
					continue;
				}
			}

			// Try 2-event pattern: Text("[<inner>") + Text("] <rest>")
			if i + 1 < raw.len()
				&& let (OwnedEvent::Text(first), OwnedEvent::Text(second)) = (&raw[i], &raw[i + 1])
				&& let Some(inner) = first.strip_prefix('[')
				&& let Some(rest) = second.strip_prefix(']')
				&& (rest.is_empty() || rest.starts_with(' '))
			{
				events.push(OwnedEvent::CheckBox(inner.to_string()));
				let rest = rest.strip_prefix(' ').unwrap_or(rest);
				if !rest.is_empty() {
					events.push(OwnedEvent::Text(rest.to_string()));
				}
				i += 2;
				continue;
			}
			// No pattern matched — continue normally
		}

		// Normalize loose list items to tight: strip Paragraph wrappers inside Items,
		// replace End(Paragraph)+Start(Paragraph) boundaries with SoftBreak.
		// This ensures loose and tight lists produce identical event structure.
		let events = normalize_list_items_tight(events);
		let events = preserve_paragraph_spacing(events);

		Self(split_blockers_from_checkboxes(events))
	}
}

/// Normalize the first paragraph in each loose list item to match tight structure.
///
/// In loose lists, pulldown_cmark wraps the title in a paragraph:
///   `Start(Item), Start(P₁), CheckBox/Text, End(P₁), Start(P₂), body, End(P₂), ...`
/// Tight items have no paragraph wrapper on the title:
///   `Start(Item), CheckBox/Text, SoftBreak, body text, ...`
///
/// This pass strips `Start(P₁)` and converts the `End(P₁)` boundary to `SoftBreak`
/// (when followed by more content). All subsequent paragraphs are preserved —
/// they provide block-level structure around elements like `Rule`, code blocks, etc.
fn normalize_list_items_tight(events: Vec<OwnedEvent>) -> Vec<OwnedEvent> {
	// Per-item state:
	//   Pending — haven't seen first Start(P) yet
	//   InFirst — inside stripped first paragraph, waiting for its End(P)
	//   Done    — first paragraph handled, pass everything through
	#[derive(Clone, Copy)]
	enum State {
		Pending,
		InFirst,
		Done,
	}

	let mut out = Vec::with_capacity(events.len());
	let mut stack: Vec<State> = Vec::new();

	let mut i = 0;
	while i < events.len() {
		match &events[i] {
			OwnedEvent::Start(OwnedTag::Item) => {
				stack.push(State::Pending);
				out.push(events[i].clone());
				i += 1;
			}
			OwnedEvent::End(OwnedTagEnd::Item) => {
				stack.pop();
				out.push(events[i].clone());
				i += 1;
			}
			// First Start(Paragraph) in a pending item → strip it
			OwnedEvent::Start(OwnedTag::Paragraph) if matches!(stack.last(), Some(State::Pending)) => {
				*stack.last_mut().unwrap() = State::InFirst;
				i += 1; // strip Start(P₁)
			}
			// End(Paragraph) closing the first (stripped) paragraph
			OwnedEvent::End(OwnedTagEnd::Paragraph) if matches!(stack.last(), Some(State::InFirst)) => {
				*stack.last_mut().unwrap() = State::Done;
				if matches!(events.get(i + 1), Some(OwnedEvent::Start(OwnedTag::Paragraph))) {
					// Followed by body paragraph → SoftBreak to bridge title and body
					out.push(OwnedEvent::SoftBreak);
				}
				i += 1; // strip End(P₁)
			}
			_ => {
				out.push(events[i].clone());
				i += 1;
			}
		}
	}
	out
}

/// Preserve blank lines between block elements by inserting `Html("\n")` after `End(Paragraph)`.
///
/// `newlines_after_paragraph: 1` in cmark options means `End(P)` only emits 1 newline.
/// When followed by another block element (Start(P), Start(Heading), etc.), the original blank line
/// is lost. We restore it by inserting a raw `\n` event, so the final output has 2 newlines (blank line).
///
/// Skipped inside list items — list item spacing is handled by normalization and cmark itself.
/// Skipped when next event is `End(...)` — that means we're exiting a scope, not starting a new block.
pub(super) fn preserve_paragraph_spacing(events: Vec<OwnedEvent>) -> Vec<OwnedEvent> {
	let mut out = Vec::with_capacity(events.len());
	let mut item_depth = 0usize;
	for i in 0..events.len() {
		match &events[i] {
			OwnedEvent::Start(OwnedTag::Item) => item_depth += 1,
			OwnedEvent::End(OwnedTagEnd::Item) => item_depth -= 1,
			_ => {}
		}
		out.push(events[i].clone());
		if item_depth == 0 && matches!(&events[i], OwnedEvent::End(OwnedTagEnd::Paragraph)) && matches!(events.get(i + 1), Some(OwnedEvent::Start(_))) {
			out.push(OwnedEvent::Html("\n".to_string()));
		}
	}
	out
}

/// Split a list after a `# Blockers` heading at the point where checkbox items begin.
///
/// pulldown_cmark merges all consecutive `- ` items into a single list, even when
/// some are plain blocker items and some are checkbox items from a semantically separate list.
/// We split them, but ONLY when all conditions are met:
/// 1. A `Marker::BlockersSection` heading immediately precedes the list
/// 2. The list starts with non-checkbox items (the actual blockers)
/// 3. At some point checkbox items begin — that's where we split
///
/// Any checkbox item after a blockers heading is NOT a blocker — it's either a linked
/// child issue or implicitly a new issue request.
///
/// Milestone lists (where checkboxes and plain refs coexist) are left intact.
fn split_blockers_from_checkboxes(events: Vec<OwnedEvent>) -> Vec<OwnedEvent> {
	let mut out = Vec::with_capacity(events.len());
	let mut i = 0;

	while i < events.len() {
		if !matches!(&events[i], OwnedEvent::Start(OwnedTag::List(_))) {
			out.push(events[i].clone());
			i += 1;
			continue;
		}

		let list_start_event = events[i].clone();
		let list_end = find_matching_end_list(&events, i);

		// Check condition 1: is this list immediately preceded by a BlockersSection heading?
		if !preceded_by_blockers_heading(&out) {
			// Not a blockers list — pass through unchanged, but recurse into nested lists
			out.push(events[i].clone());
			i += 1;
			continue;
		}

		// Walk items at depth=1, record (start_idx, end_idx, has_checkbox)
		let mut items: Vec<(usize, usize, bool)> = Vec::new();
		let mut depth = 0;
		let mut j = i;
		while j < list_end {
			match &events[j] {
				OwnedEvent::Start(OwnedTag::List(_)) => depth += 1,
				OwnedEvent::End(OwnedTagEnd::List(_)) => depth -= 1,
				OwnedEvent::Start(OwnedTag::Item) if depth == 1 => {
					let item_start = j;
					let item_end = find_matching_end_item(&events, j);
					let has_cb = item_has_checkbox(&events[item_start..item_end]);
					items.push((item_start, item_end, has_cb));
					j = item_end;
					continue;
				}
				_ => {}
			}
			j += 1;
		}

		// Need both blocker items (non-checkbox) and checkbox items to split
		let has_blocker = items.iter().any(|(_, _, has_cb)| !*has_cb);
		let has_checkbox = items.iter().any(|(_, _, has_cb)| *has_cb);

		if !has_blocker || !has_checkbox {
			out.push(events[i].clone());
			i += 1;
			continue;
		}

		// Split: non-checkbox items → blocker list, checkbox items → child issues list
		out.push(list_start_event.clone());
		for &(item_start, item_end, has_cb) in &items {
			if !has_cb {
				out.extend(events[item_start..item_end].iter().cloned());
			}
		}
		out.push(OwnedEvent::End(OwnedTagEnd::List(false)));

		out.push(list_start_event.clone());
		for &(item_start, item_end, has_cb) in &items {
			if has_cb {
				out.extend(events[item_start..item_end].iter().cloned());
			}
		}
		out.push(OwnedEvent::End(OwnedTagEnd::List(false)));

		i = list_end;
	}

	out
}

/// Check whether the events accumulated so far end with a BlockersSection heading.
/// Reconstructs the heading text from events and delegates to `Marker::decode`.
fn preceded_by_blockers_heading(out: &[OwnedEvent]) -> bool {
	// Walk backwards: expect End(Heading), then text events, then Start(Heading)
	let Some(last) = out.last() else { return false };
	let OwnedEvent::End(OwnedTagEnd::Heading(level)) = last else { return false };

	// Collect heading text by walking backwards past the End(Heading)
	let mut heading_text = String::new();
	let mut found_start = false;
	for ev in out[..out.len() - 1].iter().rev() {
		match ev {
			OwnedEvent::Start(OwnedTag::Heading { level: start_level, .. }) if start_level == level => {
				found_start = true;
				break;
			}
			OwnedEvent::Text(t) => {
				// Prepend (since we're walking backwards)
				heading_text.insert_str(0, t);
			}
			_ => break, // unexpected event inside heading
		}
	}
	if !found_start {
		return false;
	}

	// Reconstruct the line as it would appear in markdown
	let hashes: String = "#".repeat(match level {
		HeadingLevel::H1 => 1,
		HeadingLevel::H2 => 2,
		HeadingLevel::H3 => 3,
		HeadingLevel::H4 => 4,
		HeadingLevel::H5 => 5,
		HeadingLevel::H6 => 6,
	});
	let line = format!("{hashes} {heading_text}");

	matches!(super::Marker::decode(&line), Some(super::Marker::BlockersSection(_)))
}

fn find_matching_end_list(events: &[OwnedEvent], start: usize) -> usize {
	let mut depth = 0;
	for (j, ev) in events[start..].iter().enumerate() {
		match ev {
			OwnedEvent::Start(OwnedTag::List(_)) => depth += 1,
			OwnedEvent::End(OwnedTagEnd::List(_)) => {
				depth -= 1;
				if depth == 0 {
					return start + j + 1;
				}
			}
			_ => {}
		}
	}
	events.len()
}

fn find_matching_end_item(events: &[OwnedEvent], start: usize) -> usize {
	let mut depth = 0;
	for (j, ev) in events[start..].iter().enumerate() {
		match ev {
			OwnedEvent::Start(OwnedTag::Item) => depth += 1,
			OwnedEvent::End(OwnedTagEnd::Item) => {
				depth -= 1;
				if depth == 0 {
					return start + j + 1;
				}
			}
			_ => {}
		}
	}
	events.len()
}

fn item_has_checkbox(item_events: &[OwnedEvent]) -> bool {
	let mut i = 0;
	if matches!(item_events.get(i), Some(OwnedEvent::Start(OwnedTag::Item))) {
		i += 1;
	}
	matches!(item_events.get(i), Some(OwnedEvent::CheckBox(_)))
}

fn parser_options() -> pulldown_cmark::Options {
	pulldown_cmark::Options::ENABLE_TASKLISTS | pulldown_cmark::Options::ENABLE_STRIKETHROUGH
}

pub(crate) fn cmark_options() -> pulldown_cmark_to_cmark::Options<'static> {
	pulldown_cmark_to_cmark::Options {
		list_token: '-',
		newlines_after_headline: 1,
		newlines_after_paragraph: 1,
		..Default::default()
	}
}

/// Convert `&[OwnedEvent]` to `Vec<Event>` ready for `pulldown_cmark_to_cmark`.
///
/// Handles:
/// 1. `CheckBox(" ")`/`CheckBox("x")` → `TaskListMarker`
/// 2. Custom `CheckBox` → escaped `Text("[<inner>\] ")`
/// 3. Loose-list spacing: inserts `Html("\n")` between items in lists that contain checkboxes
pub(crate) fn prepare_for_render(events: &[OwnedEvent]) -> Vec<Event<'_>> {
	let mut out = Vec::with_capacity(events.len());

	// Identify which list ranges contain checkboxes (for loose inter-item spacing).
	struct ListInfo {
		start_idx: usize,
		has_checkbox: bool,
	}
	let mut list_stack: Vec<ListInfo> = Vec::new();
	let mut checkbox_lists: Vec<(usize, usize)> = Vec::new();

	for (i, ev) in events.iter().enumerate() {
		match ev {
			OwnedEvent::Start(OwnedTag::List(_)) => {
				list_stack.push(ListInfo { start_idx: i, has_checkbox: false });
			}
			OwnedEvent::CheckBox(_) =>
				if let Some(info) = list_stack.last_mut() {
					info.has_checkbox = true;
				},
			OwnedEvent::End(OwnedTagEnd::List(_)) =>
				if let Some(info) = list_stack.pop()
					&& info.has_checkbox
				{
					checkbox_lists.push((info.start_idx, i));
				},
			_ => {}
		}
	}

	// Build a set of Item end indices where we should insert Html("\n") for loose spacing.
	let mut loose_item_ends: std::collections::HashSet<usize> = std::collections::HashSet::new();
	for (list_start, list_end) in &checkbox_lists {
		let mut depth = 0;
		let mut item_ends = Vec::new();
		for (i, ev) in events[*list_start..=*list_end].iter().enumerate() {
			let abs_i = list_start + i;
			match ev {
				OwnedEvent::Start(OwnedTag::List(_)) => depth += 1,
				OwnedEvent::End(OwnedTagEnd::List(_)) => depth -= 1,
				OwnedEvent::End(OwnedTagEnd::Item) if depth == 1 => item_ends.push(abs_i),
				_ => {}
			}
		}
		if item_ends.len() > 1 {
			for &idx in &item_ends[..item_ends.len() - 1] {
				loose_item_ends.insert(idx);
			}
		}
	}

	for (i, ev) in events.iter().enumerate() {
		match ev {
			OwnedEvent::CheckBox(inner) => match inner.as_str() {
				" " => out.push(Event::TaskListMarker(false)),
				"x" => out.push(Event::TaskListMarker(true)),
				_ => out.push(Event::Text(format!("[{inner}] ").into())),
			},
			_ => out.push(ev.to_event()),
		}
		if loose_item_ends.contains(&i) {
			out.push(Event::Html("\n".into()));
		}
	}

	out
}

/// Append `content` to `out`, prefixing each line with `prefix`.
/// Preserves trailing newline from content.
pub(super) fn indent_into(out: &mut String, content: &str, prefix: &str) {
	for line in content.lines() {
		if line.is_empty() {
			out.push('\n');
		} else {
			out.push_str(prefix);
			out.push_str(line);
			out.push('\n');
		}
	}
}

/// Wrap runs of inline events in `Start(Paragraph)` / `End(Paragraph)`.
///
/// Events stored from inside list items have paragraph wrappers stripped (by normalization).
/// When rendering these events as standalone markdown (e.g., GitHub body), inline content
/// needs paragraph wrappers for proper block-level separation from subsequent elements.
pub(super) fn wrap_inline_in_paragraphs(events: Vec<OwnedEvent>) -> Vec<OwnedEvent> {
	if events.is_empty() {
		return events;
	}
	let mut out = Vec::with_capacity(events.len() + 2);
	let mut in_inline = false;

	for ev in events {
		let is_inline = matches!(
			&ev,
			OwnedEvent::Text(_)
				| OwnedEvent::Code(_)
				| OwnedEvent::InlineHtml(_)
				| OwnedEvent::InlineMath(_)
				| OwnedEvent::SoftBreak
				| OwnedEvent::HardBreak
				| OwnedEvent::Start(OwnedTag::Emphasis)
				| OwnedEvent::End(OwnedTagEnd::Emphasis)
				| OwnedEvent::Start(OwnedTag::Strong)
				| OwnedEvent::End(OwnedTagEnd::Strong)
				| OwnedEvent::Start(OwnedTag::Strikethrough)
				| OwnedEvent::End(OwnedTagEnd::Strikethrough)
				| OwnedEvent::Start(OwnedTag::Link { .. })
				| OwnedEvent::End(OwnedTagEnd::Link)
				| OwnedEvent::Start(OwnedTag::Image { .. })
				| OwnedEvent::End(OwnedTagEnd::Image)
		);
		if is_inline && !in_inline {
			out.push(OwnedEvent::Start(OwnedTag::Paragraph));
			in_inline = true;
		} else if !is_inline && in_inline {
			out.push(OwnedEvent::End(OwnedTagEnd::Paragraph));
			in_inline = false;
		}
		out.push(ev);
	}
	if in_inline {
		out.push(OwnedEvent::End(OwnedTagEnd::Paragraph));
	}
	out
}

/// Render a slice of `OwnedEvent`s to markdown using the shared cmark options.
fn render_events(events: &[OwnedEvent]) -> String {
	let prepared = prepare_for_render(events);
	let mut output = String::new();
	pulldown_cmark_to_cmark::cmark_with_options(prepared.into_iter(), &mut output, cmark_options()).expect("markdown rendering should not fail");
	output
}

impl From<Events> for String {
	fn from(events: Events) -> Self {
		render_events(&events)
	}
}

impl fmt::Display for Events {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", render_events(self))
	}
}

impl From<Vec<OwnedEvent>> for Events {
	fn from(events: Vec<OwnedEvent>) -> Self {
		Self(events)
	}
}

impl From<String> for Events {
	fn from(s: String) -> Self {
		Self::parse(&s)
	}
}

impl From<&str> for Events {
	fn from(s: &str) -> Self {
		Self::parse(s)
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_parse_simple_text() {
		let events = Events::parse("Hello world");
		assert!(!events.is_empty());
		let rendered: String = events.into();
		assert!(rendered.contains("Hello world"));
	}

	#[test]
	fn test_parse_with_formatting() {
		let events = Events::parse("Hello **bold** and `code`");
		let rendered: String = events.into();
		assert!(rendered.contains("Hello"));
		assert!(rendered.contains("bold"));
		assert!(rendered.contains("code"));
	}

	#[test]
	fn test_roundtrip_simple() {
		let original = "Simple paragraph.";
		let events = Events::parse(original);
		let rendered: String = events.into();
		assert!(rendered.contains("Simple paragraph"));
	}

	#[test]
	fn test_empty() {
		let events = Events::default();
		assert!(events.is_empty());
		assert_eq!(events.len(), 0);
	}

	#[test]
	fn blockers_list_split_from_child_issues() {
		// After # Blockers heading, non-checkbox items then child issue items (checkbox + issue marker) → split
		let events = Events::parse("# Blockers\n- a\n- b\n- [ ] item <!-- https://github.com/o/r/issues/1 -->\n");
		let list_count = events.iter().filter(|e| matches!(e, OwnedEvent::Start(OwnedTag::List(_)))).count();
		assert_eq!(list_count, 2, "blockers + child issue tight should split into 2 lists");

		let events = Events::parse("# Blockers\n- a\n- b\n\n- [ ] item <!-- https://github.com/o/r/issues/1 -->\n");
		let list_count = events.iter().filter(|e| matches!(e, OwnedEvent::Start(OwnedTag::List(_)))).count();
		assert_eq!(list_count, 2, "blockers + child issue loose should split into 2 lists");
	}

	#[test]
	fn blockers_with_checkbox_no_marker_splits() {
		// Checkbox items after blockers heading are NOT blockers — they always split out
		let events = Events::parse("# Blockers\n- a\n- b\n- [ ] just a checkbox item\n");
		let list_count = events.iter().filter(|e| matches!(e, OwnedEvent::Start(OwnedTag::List(_)))).count();
		assert_eq!(list_count, 2, "checkbox items after blockers heading must split into separate list");
	}

	#[test]
	fn milestone_mixed_list_stays_unified() {
		// Milestone: checkbox + plain ref in same list → must NOT split
		let events = Events::parse("- [ ] one item\n- ref in the same list\n");
		let list_count = events.iter().filter(|e| matches!(e, OwnedEvent::Start(OwnedTag::List(_)))).count();
		assert_eq!(list_count, 1, "milestone mixed tight should stay as 1 list");

		let events = Events::parse("- [ ] one item\n\n- ref in the same list\n");
		let list_count = events.iter().filter(|e| matches!(e, OwnedEvent::Start(OwnedTag::List(_)))).count();
		assert_eq!(list_count, 1, "milestone mixed loose should stay as 1 list");
	}

	#[test]
	fn non_blockers_mixed_list_stays_unified() {
		// Mixed list without blockers heading → must NOT split
		let events = Events::parse("- a\n- [ ] item\n");
		let list_count = events.iter().filter(|e| matches!(e, OwnedEvent::Start(OwnedTag::List(_)))).count();
		assert_eq!(list_count, 1, "mixed list without heading should stay as 1 list");
	}

	#[test]
	fn blockers_all_checkbox_stays_unified() {
		// # Blockers followed by all-checkbox list → no split needed
		let events = Events::parse("# Blockers\n- [ ] a\n- [ ] b\n");
		let list_count = events.iter().filter(|e| matches!(e, OwnedEvent::Start(OwnedTag::List(_)))).count();
		assert_eq!(list_count, 1, "all-checkbox list after blockers heading should stay as 1 list");
	}

	#[test]
	fn loose_list_no_padding_before_body() {
		let input = "- [ ] item\n\n  body text\n";
		let rendered: String = Events::parse(input).into();
		insta::assert_snapshot!(rendered, @"
		- [ ] item
		  body text
		");
	}

	#[test]
	fn rule_inside_list_item_survives_normalization() {
		let loose = "- item\n\n  body\n\n  ---\n\n  after rule\n";
		let rendered: String = Events::parse(loose).into();
		assert!(rendered.contains("---"), "Rule must survive normalization");
	}

	#[test]
	fn paragraph_spacing_preserved_at_top_level() {
		// User content with blank line between paragraphs
		let input = "First paragraph\n\nSecond paragraph\n";
		let rendered: String = Events::parse(input).into();
		insta::assert_snapshot!(rendered, @r"
		First paragraph

		Second paragraph
		");
	}

	#[test]
	fn paragraph_spacing_not_added_inside_list_items() {
		// Inside list items, spacing should NOT be added
		let input = "- [ ] item\n\n  body text\n\n  more body\n";
		let rendered: String = Events::parse(input).into();
		insta::assert_snapshot!(rendered, @r"
		- [ ] item
		  body text
		  more body
		");
	}

	#[test]
	fn blockers_starts_with_checkbox_splits() {
		// # Blockers where first item is checkbox → still splits (checkbox items are never blockers)
		let events = Events::parse("# Blockers\n- [ ] a\n- b\n");
		let list_count = events.iter().filter(|e| matches!(e, OwnedEvent::Start(OwnedTag::List(_)))).count();
		assert_eq!(list_count, 2, "checkbox-first blockers list should split");
	}
}