include-file 1.0.0

Include sections of files into Rust source code
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
// Copyright 2025 Heath Stewart.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

// cspell:ignore notextile peekable myclass

use proc_macro2::TokenStream;
use std::{fs, io};

pub fn include_textile(item: TokenStream) -> syn::Result<TokenStream> {
    super::include_file(item, collect::<fs::File>)
}

fn collect<R: io::Read>(
    name: &str,
    iter: io::Lines<io::BufReader<R>>,
) -> io::Result<(u32, Vec<String>)> {
    let mut lines = Vec::new();
    let mut in_block = false;
    let mut is_double_period = false;
    let mut start_line: u32 = 0;

    for (line_idx, line) in iter.enumerate() {
        let line = line?;
        let line_num = (line_idx + 1) as u32;

        if !in_block {
            // Look for a code block starting with bc(rust#name). or bc(rust#name)..
            // or bc[rust](#name). or bc(#name)[rust].
            let trimmed = line.trim();

            if trimmed.starts_with("bc") && has_matching_id(trimmed, name) {
                is_double_period = trimmed.contains("..");
                start_line = line_num; // content starts on this same line, after the bc directive

                // Extract content after the first space on the same line
                // Code MUST start on the same line in Textile
                if let Some(space_pos) = trimmed.find(' ') {
                    let content = &trimmed[space_pos + 1..];
                    if !content.is_empty() {
                        lines.push(content.to_string());
                        in_block = true;
                    }
                }
            }
        } else {
            let trimmed = line.trim();

            if is_double_period {
                // Double period: collect until next block command (text followed by .)
                if is_block_tag(trimmed) {
                    // Remove trailing empty lines before the block tag
                    while let Some(last) = lines.last() {
                        if last.trim().is_empty() {
                            lines.pop();
                        } else {
                            break;
                        }
                    }
                    break;
                }
                // Collect the line
                lines.push(line);
            } else {
                // Single period: collect until first blank line
                if trimmed.is_empty() {
                    break;
                }
                // Collect the line
                lines.push(line);
            }
        }
    }

    Ok((start_line, lines))
}

fn has_matching_id(line: &str, name: &str) -> bool {
    // Look for bc(rust#name). or bc(rust#name).. or bc[rust](#name). or bc(#name)[rust].
    // Examples: bc(rust#example).
    //           bc(rust#example)..
    //           bc[rust](#example).
    //           bc(#example)[rust]..

    // Pattern 1: bc(rust#name)
    let pattern1 = format!("bc(rust#{})", name);
    if let Some(pos) = line.find(&pattern1) {
        let after_pattern = &line[pos + pattern1.len()..];
        // Check if followed by . or ..
        if after_pattern.starts_with('.') || after_pattern.starts_with("..") {
            return true;
        }
    }

    // Pattern 2: bc[rust](#name)
    let pattern2 = format!("bc[rust](#{})", name);
    if let Some(pos) = line.find(&pattern2) {
        let after_pattern = &line[pos + pattern2.len()..];
        // Check if followed by . or ..
        if after_pattern.starts_with('.') || after_pattern.starts_with("..") {
            return true;
        }
    }

    // Pattern 3: bc(#name)[rust]
    let pattern3 = format!("bc(#{})[rust]", name);
    if let Some(pos) = line.find(&pattern3) {
        let after_pattern = &line[pos + pattern3.len()..];
        // Check if followed by . or ..
        if after_pattern.starts_with('.') || after_pattern.starts_with("..") {
            return true;
        }
    }

    false
}

fn is_block_tag(line: &str) -> bool {
    // Check if line starts a new textile block
    // Block tags can have formatting characters like: p<., h1>., table(class)., etc.
    // Valid formatting chars before period: <, >, =, and content in () or []
    if line.is_empty() {
        return false;
    }

    // Known block types
    let block_types = [
        "p",
        "bq",
        "bc",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "table",
        "pre",
        "notextile",
    ];

    for block_type in &block_types {
        if let Some(after_block) = line.strip_prefix(block_type) {
            // Block tag must be followed by valid formatting chars and then a period
            // Valid chars: <, >, =, and content within () or []
            let mut chars = after_block.chars().peekable();
            let mut found_period = false;

            while let Some(ch) = chars.next() {
                match ch {
                    '.' => {
                        found_period = true;
                        break;
                    }
                    '<' | '>' | '=' => {
                        // Valid alignment/formatting character, continue
                    }
                    '(' => {
                        // Parentheses can be:
                        // 1. Empty or for indentation: p(. or p((.
                        // 2. With content: table(myclass).
                        // Look ahead to check if there's content before ) or .
                        let mut depth = 1;
                        while let Some(&next_ch) = chars.peek() {
                            if next_ch == '.' {
                                // Period found, this paren is just formatting
                                break;
                            } else if next_ch == ')' {
                                chars.next(); // consume )
                                depth -= 1;
                                if depth == 0 {
                                    break;
                                }
                            } else if next_ch == '(' {
                                chars.next(); // consume (
                                depth += 1;
                            } else {
                                chars.next(); // consume content character
                            }
                        }
                    }
                    ')' => {
                        // Closing paren for indentation styling
                    }
                    '[' => {
                        // Consume everything until matching ]
                        for inner_ch in chars.by_ref() {
                            if inner_ch == ']' {
                                break;
                            }
                        }
                    }
                    _ => {
                        // Invalid character before period
                        break;
                    }
                }
            }

            if found_period {
                return true;
            }
        }
    }

    false
}

#[cfg(test)]
mod tests {
    use super::collect;
    use crate::extract;
    use std::io;

    #[test]
    fn extract_no_code_blocks() {
        let content = r#"This is a Textile file
with no code blocks at all.
Just plain text."#;
        let cursor = io::Cursor::new(content);
        let result = extract(cursor, "example", collect);
        assert!(matches!(result, Err(err) if err.kind() == io::ErrorKind::NotFound));
    }

    #[test]
    fn extract_no_matching_id() {
        let content = r#"Some text here.

bc(rust#other). fn main() {
    println!("Hello");
}

p. More text."#;
        let cursor = io::Cursor::new(content);
        let result = extract(cursor, "example", collect);
        assert!(matches!(result, Err(err) if err.kind() == io::ErrorKind::NotFound));
    }

    #[test]
    fn extract_single_period_with_content() {
        let content = r#"Some introduction text.

bc[rust](#example). println!("hello, world!");

p. Text after the block."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(result, r#"println!("hello, world!");"#);
    }
    #[test]
    fn extract_double_period_multiline() {
        let content = r#"Some introduction text.

bc(#example)[rust].. fn test() {
    assert_eq!(2 + 2, 4);
}

p. Text after the block."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"fn test() {
    assert_eq!(2 + 2, 4);
}"#
        );
    }

    #[test]
    fn extract_multiline_until_next_block() {
        let content = r#"Some introduction text.

bc[rust](#example).. let x = 42;
let y = x + 1;

bq. This is a quote block that ends the code."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"let x = 42;
let y = x + 1;"#
        );
    }

    #[test]
    fn extract_multiple_blocks_one_match() {
        let content = r#"Here's the first block:

bc(python#other). print("Not this one")

p. And here's the one we want:

bc(#example)[rust]. println!("This is the one!");

p. And another one."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(result, r#"println!("This is the one!");"#);
    }

    #[test]
    fn extract_content_on_next_line() {
        let content = r#"Text before.

bc(rust#example).. fn with_content() {
    println!("On next line");
}

p. Text after."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"fn with_content() {
    println!("On next line");
}"#
        );
    }

    #[test]
    fn extract_with_class_before_id() {
        let content = r#"Text before.

bc[rust](#example). let value = 123;

p. Text after."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(result, "let value = 123;");
    }

    #[test]
    fn extract_until_eof() {
        let content = r#"Text before.

bc(rust#example).. struct Point {
    x: i32,
    y: i32,
}"#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"struct Point {
    x: i32,
    y: i32,
}"#
        );
    }

    #[test]
    fn extract_empty_lines_within_block() {
        let content = r#"Text before.

bc(rust#example).. fn first() {}

fn second() {}

p. Text after."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"fn first() {}

fn second() {}"#
        );
    }

    #[test]
    fn extract_different_language() {
        let content = r#"Text before.

bc(python#example). print("hello")

p. Text after."#;
        let cursor = io::Cursor::new(content);
        let result = extract(cursor, "example", collect);
        assert!(matches!(result, Err(err) if err.kind() == io::ErrorKind::NotFound));
    }

    #[test]
    fn extract_ends_at_right_aligned_header() {
        let content = r#"Text before.

bc(rust#example).. let x = 1;
let y = 2;

h1>. Right Aligned Header"#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"let x = 1;
let y = 2;"#
        );
    }

    #[test]
    fn extract_ends_at_justified_paragraph() {
        let content = r#"Text before.

bc(rust#example).. fn test() {
    println!("test");
}

p<>. Justified paragraph text."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"fn test() {
    println!("test");
}"#
        );
    }

    #[test]
    fn extract_ends_at_centered_header() {
        let content = r#"Text before.

bc(rust#example).. let value = 42;

h2=. Centered Header"#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(result, "let value = 42;");
    }

    #[test]
    fn extract_ends_at_indented_paragraph() {
        let content = r#"Text before.

bc(rust#example).. struct Point {
    x: i32,
}

p(. Indented paragraph."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"struct Point {
    x: i32,
}"#
        );
    }

    #[test]
    fn extract_ends_at_table_with_class() {
        let content = r#"Text before.

bc(rust#example).. let data = vec![1, 2, 3];

table(myclass). Some table content"#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(result, "let data = vec![1, 2, 3];");
    }

    #[test]
    fn extract_ends_at_notextile_block() {
        let content = r#"Text before.

bc(rust#example).. fn example() {
    println!("code");
}

notextile. Raw content here."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"fn example() {
    println!("code");
}"#
        );
    }

    #[test]
    fn extract_bc_with_bracket_syntax() {
        let content = r#"Text before.

bc[rust](#example). let value = 100;

p. Text after."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(result, "let value = 100;");
    }

    #[test]
    fn extract_ends_at_right_padded_paragraph() {
        let content = r#"Text before.

bc(rust#example).. let x = 10;
let y = 20;

p))). Right padded paragraph."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"let x = 10;
let y = 20;"#
        );
    }

    #[test]
    fn extract_ends_at_combined_padding_paragraph() {
        let content = r#"Text before.

bc(rust#example).. fn test() {
    return 42;
}

p()). Left indent and right padding."#;
        let cursor = io::Cursor::new(content);
        let (_, result) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(
            result,
            r#"fn test() {
    return 42;
}"#
        );
    }

    #[test]
    fn extract_start_line() {
        // bc tag is on line 3; content starts on the same line.
        let content = "Text.\n\nbc(rust#example). let x = 1;\n";
        let cursor = io::Cursor::new(content);
        let (start_line, _) = extract(cursor, "example", collect).expect("expected content");
        assert_eq!(start_line, 3);
    }
}