askama_fmt 0.3.2

Formatter for Askama HTML templates
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
/// Line-by-line indentation state machine.
use crate::config::FormatOptions;
use crate::formatter::expand::BLOCK_HTML_TAGS;

const VOID_HTML_TAGS: &[&str] = &[
    "area", "base", "br", "col", "embed", "hr", "img", "input",
    "link", "meta", "param", "source", "track", "wbr",
];

fn is_void_html_tag(name: &str) -> bool {
    VOID_HTML_TAGS.iter().any(|&t| t.eq_ignore_ascii_case(name))
}

/// HTML tags whose opening tag increases indent.
fn is_indent_html_tag(name: &str) -> bool {
    BLOCK_HTML_TAGS.iter().any(|&t| t.eq_ignore_ascii_case(name))
        && !is_void_html_tag(name)
        && !"hr".eq_ignore_ascii_case(name)
        && !"br".eq_ignore_ascii_case(name)
        && !"link".eq_ignore_ascii_case(name)
        && !"meta".eq_ignore_ascii_case(name)
}

struct IndentState<'a> {
    opts: &'a FormatOptions,
    level: usize,
    in_raw: bool, // inside {% raw %} or <pre>/<script>/<style>
    raw_depth: usize,
    /// Non-None when we're inside a multi-line HTML opening tag whose `>` has
    /// not appeared yet (e.g. `<form\n  attr1\n  attr2>`).
    /// Tuple: (tag_name, is_block_level).  Block-level tags increment `level`
    /// when the closing `>` is found; inline/void tags do not.
    multi_line_tag: Option<(String, bool)>,
    /// Stack of base indent levels for open `custom_blocks` tags.
    /// Used by `custom_blocks_branch` keywords to reset each branch to the
    /// same indentation level inside the enclosing block.
    block_base_levels: Vec<usize>,
}

impl<'a> IndentState<'a> {
    fn new(opts: &'a FormatOptions) -> Self {
        Self {
            opts,
            level: 0,
            in_raw: false,
            raw_depth: 0,
            multi_line_tag: None,
            block_base_levels: Vec::new(),
        }
    }

    fn write_indent(&self, out: &mut String) {
        out.extend(std::iter::repeat_n(' ', self.opts.indent * self.level));
    }

    fn write_indent_at(&self, out: &mut String, level: usize) {
        out.extend(std::iter::repeat_n(' ', self.opts.indent * level));
    }

    /// Indentation for continuation attribute lines inside a multi-line tag.
    /// Aligns to the column after `<tagname `.
    fn write_continuation_indent(&self, out: &mut String, tag_name: &str) {
        let n = self.opts.indent * self.level + 1 + tag_name.len() + 1;
        out.extend(std::iter::repeat_n(' ', n));
    }
}

pub fn indent(html: &str, opts: &FormatOptions) -> String {
    let mut state = IndentState::new(opts);
    let mut out = String::with_capacity(html.len());


    for line in html.lines() {
        let trimmed = line.trim();

        if trimmed.is_empty() {
            out.push('\n');
            continue;
        }

        // --- Multi-line HTML opening tag continuation ---
        // Covers both block-level tags (<form>, <div>, …) and inline/void
        // tags (<input>, <a>, …) that have their `>` on a later line.
        if let Some((ref tag_name, is_block)) = state.multi_line_tag.clone() {
            if html_open_tag_closes_here(trimmed) {
                // This line has the closing `>` — tag is fully open.
                state.multi_line_tag = None;
                state.write_continuation_indent(&mut out, tag_name);
                out.push_str(trimmed);
                out.push('\n');
                // Block-level tags open an indent level; inline/void do not.
                // Self-closing (`/>`) also never opens a level.
                if is_block && !trimmed.trim_end().ends_with("/>") {
                    state.level += 1;
                }
            } else {
                // Continuation attribute line (no `>` yet).
                state.write_continuation_indent(&mut out, tag_name);
                out.push_str(trimmed);
                out.push('\n');
            }
            continue;
        }

        // Inside a raw/verbatim block: emit as-is
        if state.in_raw {
            if is_raw_block_close(trimmed) {
                state.raw_depth = state.raw_depth.saturating_sub(1);
                if state.raw_depth == 0 {
                    state.in_raw = false;
                    // Emit the closing line.  If the closing tag is the entire
                    // trimmed line (e.g. `</style>`) give it current-level
                    // indentation.  When it's embedded at the end of content
                    // (e.g. `}</style>`) keep it as-is so that the output is
                    // stable across multiple formatter passes.
                    let starts_with_close = trimmed.starts_with("</style>")
                        || trimmed.starts_with("</script>")
                        || trimmed.starts_with("</pre>")
                        || trimmed.starts_with("{%");
                    if starts_with_close {
                        state.write_indent(&mut out);
                    }
                    out.push_str(trimmed);
                    out.push('\n');
                } else {
                    out.push_str(trimmed);
                    out.push('\n');
                }
            } else {
                out.push_str(trimmed);
                out.push('\n');
            }
            continue;
        }

        // Detect raw block opening
        if is_raw_block_open(trimmed) {
            state.in_raw = true;
            state.raw_depth = 1;
            state.write_indent(&mut out);
            out.push_str(trimmed);
            out.push('\n');
            continue;
        }

        // --- Classify the line ---

        // 1. HTML closing tag at start of line → unindent before printing
        if let Some(tag) = parse_html_close_tag(trimmed) {
            if is_indent_html_tag(tag) {
                state.level = state.level.saturating_sub(1);
                state.write_indent(&mut out);
                out.push_str(trimmed);
                out.push('\n');
                // If the same line also has an open tag (e.g. </td><td>), handle that
                continue;
            }
        }

        // 2. Template tag classification
        if let Some(kw) = parse_template_keyword(trimmed) {
            // 2a. Branch keyword ("when"): resets to the enclosing match's base
            // level + 1, then pushes for content.
            if BRANCH_KEYWORDS.contains(&kw) {
                if let Some(&base) = state.block_base_levels.last() {
                    state.level = base + 1;
                    state.write_indent(&mut out);
                    out.push_str(trimmed);
                    out.push('\n');
                    state.level = base + 2;
                } else {
                    // No enclosing custom block — no-change fallback
                    state.write_indent(&mut out);
                    out.push_str(trimmed);
                    out.push('\n');
                }
                continue;
            }

            // 2b. Branch-aware end keyword ("endmatch"):
            // pops back to the base level recorded when the block was opened.
            if BRANCH_END_KEYWORDS.contains(&kw) {
                let base = state
                    .block_base_levels
                    .pop()
                    .unwrap_or_else(|| state.level.saturating_sub(1));
                state.level = base;
                state.write_indent(&mut out);
                out.push_str(trimmed);
                out.push('\n');
                continue;
            }

            // 2c. Built-in closing tag (`{% endif %}`, `{% endfor %}`, …)
            if UNINDENT_KEYWORDS.contains(&kw) {
                state.level = state.level.saturating_sub(1);
                state.write_indent(&mut out);
                out.push_str(trimmed);
                out.push('\n');
                continue;
            }

            // 3. Unindent-line tags (else, else if) → print at level-1
            if UNINDENT_LINE_KEYWORDS.contains(&kw) {
                let effective = state.level.saturating_sub(1);
                state.write_indent_at(&mut out, effective);
                out.push_str(trimmed);
                out.push('\n');
                continue;
            }

            // 4. Tags with no indent change (let, call, import, include, extends, …)
            if NO_CHANGE_KEYWORDS.contains(&kw) {
                state.write_indent(&mut out);
                out.push_str(trimmed);
                out.push('\n');
                continue;
            }

            // 5. Indent-opening template tag
            if INDENT_KEYWORDS.contains(&kw) {
                // Track base level for match so the "when" branch keyword can reset correctly
                if kw == "match" {
                    state.block_base_levels.push(state.level);
                }
                state.write_indent(&mut out);
                out.push_str(trimmed);
                out.push('\n');
                state.level += 1;
                continue;
            }
        }

        // 6. HTML opening tag → check if it increases indent
        if let Some((open_tag, is_self_closing, has_close_on_same_line)) =
            parse_html_open_tag(trimmed)
        {
            if is_indent_html_tag(open_tag) && !is_self_closing {
                // If the closing tag is also on this same line (e.g. <td>val</td>),
                // don't change the indent level.
                if has_close_on_same_line {
                    state.write_indent(&mut out);
                    out.push_str(trimmed);
                    out.push('\n');
                    continue;
                }

                let formatted = maybe_format_attributes(trimmed, state.level, opts);
                state.write_indent(&mut out);
                out.push_str(&formatted);
                out.push('\n');
                state.level += 1;
                continue;
            }
        }

        // 6b. HTML tag that doesn't close on this line — covers both block-level
        //     tags (<form>, <table>, …) and inline/void tags (<input>, <a>, …)
        //     so that continuation attribute lines get the correct alignment
        //     regardless of whether the tag opens an indent level.
        if let Some((tag_name, is_block)) = parse_unclosed_html_open_tag(trimmed) {
            state.write_indent(&mut out);
            out.push_str(trimmed);
            out.push('\n');
            state.multi_line_tag = Some((tag_name, is_block));
            continue;
        }

        // 7. Default: emit at current indent level with attribute formatting
        let formatted = maybe_format_attributes(trimmed, state.level, opts);
        state.write_indent(&mut out);
        out.push_str(&formatted);
        out.push('\n');
    }

    // Ensure single trailing newline
    let result = out.trim_end_matches('\n').to_string();
    result + "\n"
}

// ── Keyword classification ──────────────────────────────────────────────────

const INDENT_KEYWORDS: &[&str] =
    &["if", "for", "macro", "block", "filter", "with", "raw", "match"];

const UNINDENT_KEYWORDS: &[&str] =
    &["endif", "endfor", "endmacro", "endblock", "endfilter", "endwith", "endraw"];

const UNINDENT_LINE_KEYWORDS: &[&str] = &["else", "else if"];

const BRANCH_KEYWORDS: &[&str] = &["when"];

const BRANCH_END_KEYWORDS: &[&str] = &["endmatch"];

const NO_CHANGE_KEYWORDS: &[&str] = &["let", "call", "import", "include", "extends"];

// ── Tag parsers ─────────────────────────────────────────────────────────────

/// If line starts with `</tag`, return `tag` (raw, not lowercased).
fn parse_html_close_tag(line: &str) -> Option<&str> {
    let s = line.trim_start();
    if !s.starts_with("</") {
        return None;
    }
    let rest = &s[2..];
    let end = rest
        .find(|c: char| !c.is_alphanumeric() && c != '-')
        .unwrap_or(rest.len());
    if end == 0 {
        return None;
    }
    Some(&rest[..end])
}

/// Extract the keyword from a template tag line, e.g. `{% when Some with (x) %}` → `"when"`.
/// Also handles `{%- when -%}` whitespace-stripped variants.
fn parse_template_keyword(line: &str) -> Option<&str> {
    let s = line.trim();
    if !s.starts_with("{%") {
        return None;
    }
    let inner = s[2..].trim_start_matches(['-', '+', '~', ' ', '\t']);
    // "else if" is a two-word keyword
    if inner.starts_with("else if") {
        return Some("else if");
    }
    let kw = inner
        .split_whitespace()
        .next()
        .unwrap_or("")
        .trim_end_matches(['-', '+', '~']);
    if kw.is_empty() { None } else { Some(kw) }
}

/// Allocation-free check: does `text` contain `</tag>`?
fn contains_close_tag(text: &str, tag: &str) -> bool {
    let n = tag.len();
    if n + 3 > text.len() {
        return false;
    }
    text.as_bytes().windows(n + 3).any(|w| {
        w[0] == b'<' && w[1] == b'/'
            && w[n + 2] == b'>'
            && w[2..n + 2].eq_ignore_ascii_case(tag.as_bytes())
    })
}

/// Returns `(tag_name, is_self_closing, has_matching_close_on_same_line)`.
/// `tag_name` is a slice into `line` (raw, not lowercased).
fn parse_html_open_tag(line: &str) -> Option<(&str, bool, bool)> {
    let s = line.trim_start();
    if !s.starts_with('<') || s.starts_with("</") || s.starts_with("<!") || s.starts_with("<?") {
        return None;
    }
    let rest = &s[1..];
    let end = rest
        .find(|c: char| !c.is_alphanumeric() && c != '-')
        .unwrap_or(rest.len());
    if end == 0 {
        return None;
    }
    let tag = &rest[..end];  // raw, not lowercased

    // Use the shared scanner — correctly skips {%...%} containing `>`.
    let close_pos = super::find_html_tag_close(s)?;

    // Self-closing: the byte immediately before `>` is `/`.
    let self_closing = close_pos > 0 && s.as_bytes()[close_pos - 1] == b'/';

    // Check if there's a matching close tag after the opening tag.
    let after_open = &s[close_pos + 1..];
    let has_close = contains_close_tag(after_open, tag);

    Some((tag, self_closing, has_close))
}

fn is_raw_block_open(line: &str) -> bool {
    let s = line.trim();
    // Only open a raw block if the closing tag is NOT also on this line.
    for (open, close) in &[
        ("<pre", "</pre>"),
        ("<script", "</script>"),
        ("<style", "</style>"),
    ] {
        if s.starts_with(open) && !s.contains(close) {
            return true;
        }
    }
    if let Some(kw) = parse_template_keyword(s) {
        return kw == "raw";
    }
    false
}

/// If the line opens an HTML tag whose `>` is NOT on this line, returns
/// `(tag_name, is_block_level)`.  Works for both block-level tags (<form>…)
/// and inline/void tags (<input>, <a>…) so that multi-line attribute
/// continuation lines are always aligned correctly.
fn parse_unclosed_html_open_tag(line: &str) -> Option<(String, bool)> {
    let s = line.trim_start();
    if !s.starts_with('<') || s.starts_with("</") || s.starts_with("<!") || s.starts_with("<?") {
        return None;
    }
    let rest = &s[1..];
    let end = rest
        .find(|c: char| !c.is_alphanumeric() && c != '-')
        .unwrap_or(rest.len());
    if end == 0 {
        return None;
    }
    let tag = rest[..end].to_string();
    // Use the shared scanner — `{%...%}` containing `>` is correctly skipped.
    if super::find_html_tag_close(s).is_some() {
        return None;
    }
    let is_block = is_indent_html_tag(&tag);
    Some((tag, is_block))
}

/// Returns true if `line` closes a pending multi-line HTML opening tag, i.e.
/// it contains an unquoted `>` outside any template tag or quoted value.
fn html_open_tag_closes_here(line: &str) -> bool {
    super::find_html_tag_close(line.trim()).is_some()
}

fn is_raw_block_close(line: &str) -> bool {
    let s = line.trim();
    // The closing tag can appear anywhere on the line (e.g. `}</style>`).
    if s.contains("</pre>") || s.contains("</script>") || s.contains("</style>") {
        return true;
    }
    if let Some(kw) = parse_template_keyword(s) {
        return kw == "endraw";
    }
    false
}

// ── Attribute formatting ─────────────────────────────────────────────────────

pub fn maybe_format_attributes(line: &str, level: usize, opts: &FormatOptions) -> String {
    let s = line.trim();
    if !s.starts_with('<') || s.starts_with("</") || s.starts_with("<!") {
        return s.to_string();
    }

    let rest = &s[1..];
    let name_end = rest
        .find(|c: char| !c.is_alphanumeric() && c != '-')
        .unwrap_or(rest.len());
    let tag_name = &rest[..name_end];

    if !s[1 + name_end..].starts_with(|c: char| c.is_whitespace()) {
        return s.to_string();
    }

    let (tag_only, after_close) = split_tag_from_content(s);
    let attrs = parse_attributes(tag_only);
    if attrs.len() < 2 {
        return s.to_string();
    }


    // Sort attributes alphabetically (unhinged default: on).
    // Skip if template syntax is present — reordering {% if %}...{% endif %}
    // conditional attributes would break semantics.
    let attrs = if opts.sort_attributes {
        sort_attributes(attrs)
    } else {
        attrs
    };

    let is_self_closing = tag_only.trim_end().ends_with("/>");
    let close = if is_self_closing { " />" } else { ">" };

    // Reconstruct the tag with sorted attributes and check line length.
    let tag_sorted = format!("<{} {}{}", tag_name, attrs.join(" "), close);
    let indent_len = opts.indent * level;
    if indent_len + tag_sorted.len() <= opts.max_line_length {
        return if after_close.is_empty() {
            tag_sorted
        } else {
            format!("{}{}", tag_sorted, after_close)
        };
    }

    // Break: align subsequent attributes under the first attribute column.
    let align = " ".repeat(indent_len + 1 + tag_name.len() + 1);
    let mut out_lines: Vec<String> = attrs
        .iter()
        .enumerate()
        .map(|(i, attr)| {
            if i == 0 {
                format!("<{} {}", tag_name, attr)
            } else {
                format!("{}{}", align, attr)
            }
        })
        .collect();

    if let Some(last) = out_lines.last_mut() {
        last.push_str(close);
        if !after_close.is_empty() {
            last.push_str(after_close);
        }
    }
    out_lines.join("\n")
}


/// Split an HTML tag string into the `<tag attrs>` portion and anything after `>`.
/// e.g. `<a href="x">text</a>` → (`<a href="x">`, `text</a>`)
fn split_tag_from_content(s: &str) -> (&str, &str) {
    match super::find_html_tag_close(s) {
        Some(pos) => (&s[..pos + 1], &s[pos + 1..]),
        None => (s, ""),
    }
}

/// Very simple attribute parser: splits on whitespace boundaries respecting quotes
/// and template tags `{{ }}` / `{% %}`.
fn parse_attributes(tag: &str) -> Vec<String> {
    let start = tag.find(|c: char| c.is_whitespace()).unwrap_or(tag.len());
    // Use the shared scanner for `>` — handles {%...%} with `>` inside and
    // multi-byte characters (returns a correct byte offset).
    let end = super::find_html_tag_close(&tag[start..])
        .map(|rel| start + rel)
        .unwrap_or(tag.len());

    // Strip trailing ` /` from self-closing tags so the `/` is not treated as
    // a separate attribute token.
    let attrs_raw = &tag[start..end];
    let attrs_str = attrs_raw.trim_end_matches('/').trim_end();
    split_attrs(attrs_str)
}

/// Sort attributes alphabetically by name. Skips reordering if any attribute
/// contains template syntax (`{%` or `{{`) — those are conditional attribute
/// injections whose relative order is load-bearing.
fn sort_attributes(mut attrs: Vec<String>) -> Vec<String> {
    if attrs.iter().any(|a| a.contains("{%") || a.contains("{{")) {
        return attrs;
    }
    attrs.sort_by(|a, b| {
        let ka = a.split('=').next().unwrap_or(a).trim();
        let kb = b.split('=').next().unwrap_or(b).trim();
        ka.to_lowercase().cmp(&kb.to_lowercase())
    });
    attrs
}

fn split_attrs(s: &str) -> Vec<String> {
    let mut attrs = Vec::new();
    let mut current = String::new();
    let mut in_q: Option<char> = None;
    let mut depth_tmpl = 0usize;
    let chars: Vec<char> = s.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let c = chars[i];
        match in_q {
            Some(q) if c == q => {
                current.push(c);
                in_q = None;
            }
            Some(_) => {
                current.push(c);
            }
            None => {
                if c == '{'
                    && chars
                        .get(i + 1)
                        .copied()
                        .is_some_and(|n| n == '{' || n == '%')
                {
                    depth_tmpl += 1;
                    current.push(c);
                } else if depth_tmpl > 0 && (c == '}' || c == '%') && chars.get(i + 1) == Some(&'}')
                {
                    depth_tmpl -= 1;
                    current.push(c);
                } else if depth_tmpl == 0 && c.is_whitespace() {
                    let trimmed = current.trim().to_string();
                    if !trimmed.is_empty() {
                        attrs.push(trimmed);
                    }
                    current.clear();
                } else {
                    if c == '"' || c == '\'' {
                        in_q = Some(c);
                    }
                    current.push(c);
                }
            }
        }
        i += 1;
    }
    let trimmed = current.trim().to_string();
    if !trimmed.is_empty() {
        attrs.push(trimmed);
    }
    attrs
}