acdc-parser 0.8.0

`AsciiDoc` parser using PEG grammars
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
use std::{
    path::{Path, PathBuf},
    str::FromStr,
};

#[cfg(feature = "network")]
use std::{fs::File, io};

use url::Url;

use crate::{
    Options, Preprocessor, SafeMode,
    error::{Error, Positioning, SourceLocation},
    model::{HEADER, LeveloffsetRange, Position, SourceRange, substitute},
};

use super::tag::{DELIMITERS, Filter as TagFilter, Name as TagName, apply_tag_filters};

/**
The format of an include directive is the following:

`include::target[leveloffset=offset,lines=ranges,tag(s)=name(s),indent=depth,encoding=encoding,opts=optional]`

The target is required. The target may be an absolute path, a path relative to the
current document, or a URL.

The include directive can be escaped.

If you don't want the include directive to be processed, you must escape it using a
backslash.

`\include::just-an-example.ext[]`

Escaping the directive is necessary even if it appears in a verbatim block since it's
not aware of the surrounding document structure.
*/
#[derive(Debug)]
pub(crate) struct Include {
    file_parent: PathBuf,
    target: Target,
    level_offset: Option<isize>,
    line_range: Vec<LinesRange>,
    tags: Vec<TagName>,
    indent: Option<usize>,
    encoding: Option<String>,
    opts: Vec<String>,
    options: Options,
    // Location information for error reporting
    line_number: usize,
    current_offset: usize,
    current_file: Option<PathBuf>,
}

/// A line range that an include may specify.
///
/// If the range contains `..` then it is a range of lines, if not, it is parsed as a
/// single line.
///
/// There can be multiple of these in an include definition.
#[derive(Debug)]
enum LinesRange {
    /// A single line
    Single(usize),

    /// A range of lines
    Range(usize, isize),
}

/// The target of the include, which can be a filesystem path pointing to a file, or a
/// url.
///
/// NOTE: Urls will only be fetched if the attribute `allow-uri-read` is set to `true` (or
/// present).
#[derive(Debug)]
pub(crate) enum Target {
    Path(PathBuf),
    Url(Url),
}

/// Location context for error reporting in include directives
#[derive(Debug, Clone, Copy)]
struct LocationContext<'a> {
    line_number: usize,
    current_offset: usize,
    current_file: Option<&'a Path>,
}

peg::parser! {
    grammar include_parser(
        path: &std::path::Path,
        options: &Options,
        location: LocationContext<'_>
    ) for str {
        pub(crate) rule include() -> Result<Include, Error>
            = "include::" target:target() "[" attrs:attributes()? "]" {
                let target_raw = substitute(&target, HEADER, &options.document_attributes);
                let target =
                    if target_raw.starts_with("http://") || target_raw.starts_with("https://") {
                        Target::Url(Url::parse(&target_raw)?)
                    } else {
                        Target::Path(PathBuf::from(target_raw))
                    };

                let mut include = Include {
                    file_parent: path.to_path_buf(),
                    target,
                    level_offset: None,
                    line_range: Vec::new(),
                    tags: Vec::new(),
                    indent: None,
                    encoding: None,
                    opts: Vec::new(),
                    options: options.clone(),
                    line_number: location.line_number,
                    current_offset: location.current_offset,
                    current_file: location.current_file.map(Path::to_path_buf),
                };
                if let Some(attrs) = attrs {
                    include.parse_attributes(attrs)?;
                }
                Ok(include)
            }

        rule target() -> String
            = t:$((!['[' | ' ' | '\t'] [_])+) {
                t.to_string()
            }

        rule attributes() -> Vec<(String, String)>
            = pair:attribute_pair() pairs:("," p:attribute_pair() { p })* {
                let mut attrs = vec![pair];
                attrs.extend(pairs);
                attrs
            }

        rule attribute_pair() -> (String, String)
            = k:attribute_key() "=" v:attribute_value() {
                (k, v)
            }

        rule attribute_key() -> String
            // Note: "tags" must come before "tag" due to PEG's ordered choice
            = k:$("leveloffset" / "lines" / "tags" / "tag" / "indent" / "encoding" / "opts") {
                k.to_string()
            }

        rule attribute_value() -> String
            = "\"" v:$((!['"'] [_])*) "\"" { v.to_string() }
        / v:$((![','] ![']'] [_])*) { v.to_string() }
    }
}

impl FromStr for LinesRange {
    type Err = Error;

    fn from_str(line_range: &str) -> Result<Self, Self::Err> {
        // FromStr trait implementation for backward compatibility.
        // Prefer using LinesRange::parse() with location info for better error messages.
        Self::from_str_with_location(line_range, None)
    }
}

impl LinesRange {
    /// Helper to create error with location information
    fn create_error(line_range: &str, location: Option<(usize, usize, Option<&Path>)>) -> Error {
        let (line_number, _current_offset, current_file) = location.unwrap_or((1, 0, None));
        Error::InvalidLineRange(
            Box::new(SourceLocation {
                file: current_file.map(Path::to_path_buf),
                positioning: Positioning::Position(Position {
                    line: line_number,
                    column: 1,
                }),
            }),
            line_range.to_string(),
        )
    }

    /// Parse a single line range string with optional location info.
    fn from_str_with_location(
        line_range: &str,
        location: Option<(usize, usize, Option<&Path>)>,
    ) -> Result<Self, Error> {
        if line_range.contains("..") {
            let mut parts = line_range.split("..");
            let start = parts
                .next()
                .ok_or_else(|| Self::create_error(line_range, location))?
                .parse()
                .map_err(|_| Self::create_error(line_range, location))?;
            let end = parts
                .next()
                .ok_or_else(|| Self::create_error(line_range, location))?
                .parse()
                .map_err(|_| Self::create_error(line_range, location))?;
            Ok(LinesRange::Range(start, end))
        } else {
            Ok(LinesRange::Single(line_range.parse().map_err(|e| {
                tracing::error!(?line_range, ?e, "Failed to parse line range");
                Self::create_error(line_range, location)
            })?))
        }
    }

    /// Parse line ranges (possibly multiple, separated by `;` or `,`) with location info.
    fn parse(
        value: &str,
        line_number: usize,
        current_offset: usize,
        current_file: Option<&Path>,
    ) -> Result<Vec<Self>, Error> {
        let location = Some((line_number, current_offset, current_file));

        let separator = if value.contains(';') {
            ';'
        } else if value.contains(',') {
            ','
        } else {
            // Single range, no separator
            return Ok(vec![Self::from_str_with_location(value, location)?]);
        };

        value
            .split(separator)
            .map(|part| Self::from_str_with_location(part, location))
            .collect()
    }
}

/// Result of processing an include directive.
///
/// Contains the included lines and any leveloffset that should apply to them.
#[derive(Debug)]
pub(crate) struct IncludeResult {
    pub(crate) lines: Vec<String>,
    /// The effective leveloffset value to apply to this included content.
    /// This is the sum of the current document's leveloffset and the include's leveloffset.
    pub(crate) effective_leveloffset: Option<isize>,
    /// Leveloffset ranges from nested includes within this included file.
    /// These need to be merged into the parent's ranges with adjusted byte offsets.
    pub(crate) nested_leveloffset_ranges: Vec<LeveloffsetRange>,
    /// The resolved file path of the included content.
    pub(crate) file: Option<PathBuf>,
    /// Source ranges from nested includes within this included file.
    /// These need to be merged into the parent's ranges with adjusted byte offsets.
    pub(crate) nested_source_ranges: Vec<SourceRange>,
}

impl Include {
    fn parse_attributes(&mut self, attributes: Vec<(String, String)>) -> Result<(), Error> {
        for (key, value) in attributes {
            match key.as_ref() {
                "leveloffset" => {
                    self.level_offset = Some(value.parse().map_err(|_| {
                        Error::InvalidLevelOffset(
                            Box::new(SourceLocation {
                                file: self.current_file.clone(),
                                positioning: Positioning::Position(Position {
                                    line: self.line_number,
                                    column: 1,
                                }),
                            }),
                            value.clone(),
                        )
                    })?);
                }
                "lines" => {
                    self.line_range.extend(LinesRange::parse(
                        &value,
                        self.line_number,
                        self.current_offset,
                        self.current_file.as_deref(),
                    )?);
                }
                "tag" => self.tags.push(TagName::from(value)),
                "tags" => {
                    self.tags.extend(value.split(DELIMITERS).map(TagName::from));
                }
                "indent" => {
                    self.indent = Some(value.parse().map_err(|_| {
                        Error::InvalidIndent(
                            Box::new(SourceLocation {
                                file: self.current_file.clone(),
                                positioning: Positioning::Position(Position {
                                    line: self.line_number,
                                    column: 1,
                                }),
                            }),
                            value.clone(),
                        )
                    })?);
                }
                "encoding" => {
                    self.encoding = Some(value.clone());
                }
                "opts" => {
                    self.opts.extend(value.split(',').map(str::to_string));
                }
                unknown => {
                    tracing::error!(?unknown, "unknown attribute key in include directive");
                    return Err(Error::InvalidIncludeDirective(
                        Box::new(SourceLocation {
                            file: self.current_file.clone(),
                            positioning: Positioning::Position(Position {
                                line: self.line_number,
                                column: 1,
                            }),
                        }),
                        unknown.to_string(),
                    ));
                }
            }
        }
        Ok(())
    }

    pub(crate) fn parse(
        file_parent: &Path,
        line: &str,
        line_number: usize,
        line_start_offset: usize,
        current_file: Option<&Path>,
        options: &Options,
    ) -> Result<Self, Error> {
        let location = LocationContext {
            line_number,
            current_offset: line_start_offset,
            current_file,
        };

        include_parser::include(line, file_parent, options, location).map_err(|e| {
            tracing::error!(?line, error=?e, "failed to parse include directive");
            let location = e.location;
            Error::Parse(
                Box::new(crate::SourceLocation {
                    file: current_file.map(Path::to_path_buf),
                    positioning: crate::Positioning::Position(Position {
                        // Adjust line number to be relative to the document
                        // PEG parser location.line is always 1 for a single line parse
                        line: line_number,
                        column: location.column,
                    }),
                }),
                e.expected.to_string(),
            )
        })?
    }

    /// Resolve the target path, handling URL downloads if needed.
    /// Returns Ok(None) if the target is intentionally skipped (e.g., disabled URL includes).
    /// Returns Err for actual failures (network errors, file I/O errors).
    fn resolve_target_path(&self) -> Result<Option<PathBuf>, Error> {
        match &self.target {
            Target::Path(path) => Ok(Some(self.file_parent.join(path))),
            Target::Url(url) => self.resolve_url_target(url),
        }
    }

    /// Resolve a URL target by downloading to a temp file.
    /// Returns Ok(None) if URL includes are disabled (safe mode, missing attribute).
    /// Returns Err for actual failures (network errors, file I/O errors).
    #[allow(clippy::unnecessary_wraps)] // Err is used when "network" feature is enabled
    fn resolve_url_target(&self, url: &Url) -> Result<Option<PathBuf>, Error> {
        if self.options.safe_mode > SafeMode::Server {
            tracing::warn!(safe_mode=?self.options.safe_mode, "URL includes are disabled by default. If you want to enable them, must run in `SERVER` mode or less.");
            return Ok(None);
        }
        if self
            .options
            .document_attributes
            .get("allow-uri-read")
            .is_none()
        {
            tracing::warn!(
                "URL includes are disabled by default. If you want to enable them, set the 'allow-uri-read' attribute to 'true' in the document attributes or in the command line."
            );
            return Ok(None);
        }

        #[cfg(not(feature = "network"))]
        {
            tracing::warn!(url=?url, "network support is disabled, cannot fetch remote includes");
            Ok(None)
        }

        #[cfg(feature = "network")]
        {
            let mut temp_path = std::env::temp_dir();
            let Some(file_name) = url.path_segments().and_then(std::iter::Iterator::last) else {
                tracing::error!(url=?url, "failed to extract file name from URL");
                return Ok(None);
            };
            temp_path.push(file_name);

            let mut response = ureq::get(url.as_str())
                .call()
                .map_err(|e| Error::HttpRequest(e.to_string()))?;
            let mut file = File::create(&temp_path)?;
            io::copy(&mut response.body_mut().as_reader(), &mut file)?;

            tracing::debug!(?temp_path, url=?url, "downloaded file from URL");
            Ok(Some(temp_path))
        }
    }

    /// Apply tag and line range filters to content lines.
    fn apply_content_filters(&self, content_lines: &[String]) -> Vec<String> {
        let mut lines = Vec::new();

        if !self.tags.is_empty() {
            let filters: Vec<TagFilter> = self
                .tags
                .iter()
                .map(|t| TagFilter::parse(t.as_str()))
                .collect();
            let selected_indices = apply_tag_filters(content_lines, &filters);

            if self.line_range.is_empty() {
                for idx in selected_indices {
                    if let Some(line) = content_lines.get(idx) {
                        lines.push(line.clone());
                    }
                }
            } else {
                let line_range_indices = self.collect_line_range_indices(content_lines.len());
                for idx in selected_indices {
                    if line_range_indices.contains(&idx)
                        && let Some(line) = content_lines.get(idx)
                    {
                        lines.push(line.clone());
                    }
                }
            }
        } else if self.line_range.is_empty() {
            lines.extend(content_lines.iter().cloned());
        } else {
            self.extend_lines_with_ranges(content_lines, &mut lines);
        }

        lines
    }

    fn apply_indent(lines: &[String], indent: usize) -> Vec<String> {
        let min_indent = lines
            .iter()
            .filter(|line| !line.trim().is_empty())
            .map(|line| line.len() - line.trim_start().len())
            .min()
            .unwrap_or(0);

        let prefix = " ".repeat(indent);
        lines
            .iter()
            .map(|line| {
                if line.trim().is_empty() {
                    String::new()
                } else {
                    let stripped = if min_indent > 0 {
                        &line[min_indent..]
                    } else {
                        line.as_str()
                    };
                    format!("{prefix}{stripped}")
                }
            })
            .collect()
    }

    /// Read and process content from a file, returning the text and any nested ranges.
    ///
    /// For `AsciiDoc` files, this recursively processes includes and returns leveloffset
    /// and source ranges from nested includes. For non-`AsciiDoc` files, returns just the
    /// normalized content.
    pub(crate) fn read_content_from_file(
        &self,
        file_path: &Path,
    ) -> Result<(String, Vec<LeveloffsetRange>, Vec<SourceRange>), Error> {
        let content =
            crate::preprocessor::read_and_decode_file(file_path, self.encoding.as_deref())?;
        if let Some(ext) = file_path.extension() &&
            // If the file is recognized as an AsciiDoc file (i.e., it has one of the
            // following extensions: .asciidoc, .adoc, .ad, .asc, or .txt) additional
            // normalization and processing is performed. First, all trailing whitespace
            // and endlines are removed from each line and replaced with a Unix line feed.
            // This normalization is important to how an AsciiDoc processor works. Next,
            // the AsciiDoc processor runs the preprocessor on the lines, looking for and
            // interpreting the following directives:
            //
            // * includes
            //
            // * preprocessor conditionals (e.g., ifdef)
            //
            // Running the preprocessor on the included content allows includes to be nested, thus
            // provides lot of flexibility in constructing radically different documents with a single
            // primary document and a few command line attributes.
             ["adoc", "asciidoc", "ad", "asc", "txt"].contains(&ext.to_string_lossy().as_ref())
        {
            // For nested AsciiDoc includes, return the text and any nested ranges.
            // This enables proper accumulation through nested includes.
            return super::Preprocessor
                .process_inner(&content, Some(file_path), &self.options)
                .map(|result| (result.text, result.leveloffset_ranges, result.source_ranges))
                .map_err(|error| {
                    tracing::error!(path=?file_path, ?error, "failed to process file");
                    error
                });
        }

        // For non-AsciiDoc files, normalize the content and return empty nested ranges.
        Ok((Preprocessor::normalize(&content), Vec::new(), Vec::new()))
    }

    pub(crate) fn lines(&self) -> Result<IncludeResult, Error> {
        // Resolve target path (handles both file paths and URL downloads)
        let Some(path) = self.resolve_target_path()? else {
            return Ok(IncludeResult {
                lines: Vec::new(),
                effective_leveloffset: None,
                nested_leveloffset_ranges: Vec::new(),
                file: None,
                nested_source_ranges: Vec::new(),
            });
        };

        // If the path doesn't exist, return empty lines (never fail parsing due to include)
        if !path.exists() {
            if !self.opts.contains(&"optional".to_string()) {
                tracing::warn!(path=?path, "file is missing - include directive won't be processed");
            }
            return Ok(IncludeResult {
                lines: Vec::new(),
                effective_leveloffset: None,
                nested_leveloffset_ranges: Vec::new(),
                file: None,
                nested_source_ranges: Vec::new(),
            });
        }

        let (content, nested_leveloffset_ranges, nested_source_ranges) =
            self.read_content_from_file(&path)?;
        let effective_leveloffset = self.calculate_effective_leveloffset();

        let content_lines = content.lines().map(str::to_string).collect::<Vec<_>>();
        let lines = self.apply_content_filters(&content_lines);
        let lines = if let Some(indent) = self.indent {
            Self::apply_indent(&lines, indent)
        } else {
            lines
        };

        Ok(IncludeResult {
            lines,
            effective_leveloffset,
            nested_leveloffset_ranges,
            file: Some(path),
            nested_source_ranges,
        })
    }

    /// Calculate the effective leveloffset for this include.
    /// This is the sum of the current document's leveloffset and the include's leveloffset.
    fn calculate_effective_leveloffset(&self) -> Option<isize> {
        self.level_offset.map(|level_offset| {
            let current_offset = self
                .options
                .document_attributes
                .get_string("leveloffset")
                .and_then(|s| s.parse::<isize>().ok())
                .unwrap_or(0);

            current_offset + level_offset
        })
    }

    fn validate_line_number(num: usize) -> Option<usize> {
        if num < 1 {
            tracing::warn!(?num, "invalid line number in include directive");
            None
        } else {
            Some(num - 1)
        }
    }

    fn resolve_end_line(end: isize, max_size: usize) -> Option<usize> {
        match end {
            -1 => Some(max_size),
            n if n > 0 => match usize::try_from(n - 1) {
                Ok(val) => Some(val),
                Err(e) => {
                    tracing::error!(?end, ?e, "failed to cast end line number to usize");
                    None
                }
            },
            _ => {
                tracing::error!(?end, "invalid end line number in include directive");
                None
            }
        }
    }

    /// Collects all line indices that would be selected by the line ranges.
    fn collect_line_range_indices(
        &self,
        content_lines_count: usize,
    ) -> std::collections::HashSet<usize> {
        let mut indices = std::collections::HashSet::new();
        for line in &self.line_range {
            match line {
                LinesRange::Single(line_number) => {
                    if let Some(idx) = Self::validate_line_number(*line_number) {
                        if idx < content_lines_count {
                            indices.insert(idx);
                        }
                    }
                }
                LinesRange::Range(start, end) => {
                    let Some(start_idx) = Self::validate_line_number(*start) else {
                        continue;
                    };
                    let Some(end_idx) = Self::resolve_end_line(*end, content_lines_count) else {
                        continue;
                    };

                    if start_idx < content_lines_count
                        && end_idx < content_lines_count
                        && start_idx <= end_idx
                    {
                        for i in start_idx..=end_idx {
                            indices.insert(i);
                        }
                    }
                }
            }
        }
        indices
    }

    pub(crate) fn extend_lines_with_ranges(
        &self,
        content_lines: &[String],
        lines: &mut Vec<String>,
    ) {
        let content_lines_count = content_lines.len();
        for line in &self.line_range {
            match line {
                LinesRange::Single(line_number) => {
                    if let Some(idx) = Self::validate_line_number(*line_number)
                        && idx < content_lines_count
                        && let Some(line) = content_lines.get(idx)
                    {
                        lines.push(line.clone());
                    }
                }
                LinesRange::Range(start, end) => {
                    let Some(start_idx) = Self::validate_line_number(*start) else {
                        continue;
                    };
                    let Some(end_idx) = Self::resolve_end_line(*end, content_lines_count) else {
                        continue;
                    };

                    if start_idx < content_lines_count
                        && end_idx < content_lines_count
                        && start_idx <= end_idx
                        && let Some(new_lines) = content_lines.get(start_idx..=end_idx)
                    {
                        lines.extend_from_slice(new_lines);
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn test_parse_simple_include() -> Result<(), Error> {
        let path = PathBuf::from("/tmp");
        let line = "include::target.adoc[]";
        let options = Options::default();
        let include = Include::parse(&path, line, 1, 0, None, &options)?;

        assert!(matches!(
            include.target,
            Target::Path(ref path) if path.as_path() == Path::new("target.adoc")
        ));
        Ok(())
    }

    #[test]
    fn test_parse_include_with_attributes() -> Result<(), Error> {
        let path = PathBuf::from("/tmp");
        let line = "include::target.adoc[leveloffset=+1,lines=1..5,tag=example]";
        let options = Options::default();
        let include = Include::parse(&path, line, 1, 0, None, &options)?;

        assert_eq!(include.level_offset, Some(1));
        assert_eq!(include.tags, vec![TagName::from("example")]);
        assert!(!include.line_range.is_empty());
        Ok(())
    }

    #[test]
    fn test_parse_include_with_url() -> Result<(), Error> {
        let path = PathBuf::from("/tmp");
        let line = "include::https://example.com/doc.adoc[]";
        let options = Options::default();
        let include = Include::parse(&path, line, 1, 0, None, &options)?;

        assert!(matches!(
            include.target,
            Target::Url(url) if url.as_str() == "https://example.com/doc.adoc"
        ));
        Ok(())
    }

    #[test]
    fn test_parse_quoted_attributes() -> Result<(), Error> {
        let path = PathBuf::from("/tmp");
        let line = r#"include::target.adoc[tag="example code",encoding="utf-8"]"#;
        let options = Options::default();
        let include = Include::parse(&path, line, 1, 0, None, &options)?;

        assert_eq!(include.tags, vec![TagName::from("example code")]);
        assert_eq!(include.encoding, Some("utf-8".to_string()));
        Ok(())
    }

    #[test]
    fn test_parse_include_with_tags_attribute() -> Result<(), Error> {
        let path = PathBuf::from("/tmp");
        let line = "include::target.adoc[tags=intro;main;conclusion]";
        let options = Options::default();
        let include = Include::parse(&path, line, 1, 0, None, &options)?;

        assert_eq!(
            include.tags,
            vec![
                TagName::from("intro"),
                TagName::from("main"),
                TagName::from("conclusion")
            ]
        );
        Ok(())
    }

    #[test]
    fn test_parse_include_with_negated_tag() -> Result<(), Error> {
        let path = PathBuf::from("/tmp");
        let line = "include::target.adoc[tags=*;!debug]";
        let options = Options::default();
        let include = Include::parse(&path, line, 1, 0, None, &options)?;

        assert_eq!(
            include.tags,
            vec![TagName::from("*"), TagName::from("!debug")]
        );
        Ok(())
    }

    #[test]
    fn test_parse_include_with_wildcard() -> Result<(), Error> {
        let path = PathBuf::from("/tmp");
        let line = "include::target.adoc[tags=**]";
        let options = Options::default();
        let include = Include::parse(&path, line, 1, 0, None, &options)?;

        assert_eq!(include.tags, vec![TagName::from("**")]);
        Ok(())
    }

    #[test]
    fn test_parse_include_with_indent() -> Result<(), Error> {
        let path = PathBuf::from("/tmp");
        let line = "include::target.adoc[indent=4]";
        let options = Options::default();
        let include = Include::parse(&path, line, 1, 0, None, &options)?;

        assert_eq!(include.indent, Some(4));
        Ok(())
    }

    #[test]
    fn test_apply_indent_basic() {
        // min indent is 0 (def hello, end), so indent=4 adds 4 spaces to all
        let lines = vec![
            "def hello".to_string(),
            "  puts \"Hello\"".to_string(),
            "end".to_string(),
        ];
        let result = Include::apply_indent(&lines, 4);
        assert_eq!(
            result,
            vec!["    def hello", "      puts \"Hello\"", "    end",]
        );
    }

    #[test]
    fn test_apply_indent_zero() {
        // min indent is 2, so indent=0 strips 2 spaces from all lines
        let lines = vec![
            "  def hello".to_string(),
            "    puts \"Hello\"".to_string(),
            "  end".to_string(),
        ];
        let result = Include::apply_indent(&lines, 0);
        assert_eq!(result, vec!["def hello", "  puts \"Hello\"", "end",]);
    }

    #[test]
    fn test_apply_indent_empty_lines() {
        // min indent is 0 (def hello, end), empty/whitespace-only lines become empty
        let lines = vec![
            "def hello".to_string(),
            String::new(),
            "  puts \"Hello\"".to_string(),
            "   ".to_string(),
            "end".to_string(),
        ];
        let result = Include::apply_indent(&lines, 2);
        assert_eq!(
            result,
            vec!["  def hello", "", "    puts \"Hello\"", "", "  end",]
        );
    }

    #[test]
    fn test_apply_indent_mixed_whitespace() {
        // min indent is 1 (tab counts as 1 char), strips 1 char from all
        let lines = vec![
            "\tdef hello".to_string(),
            "\t\tputs \"Hello\"".to_string(),
            "\tend".to_string(),
        ];
        let result = Include::apply_indent(&lines, 2);
        assert_eq!(result, vec!["  def hello", "  \tputs \"Hello\"", "  end",]);
    }
}