askama_fmt 0.1.0

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

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

fn is_void_html_tag(name: &str) -> bool {
    matches!(
        name,
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
    )
}

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)>,
}

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

    fn indent(&self) -> String {
        " ".repeat(self.opts.indent * self.level)
    }

    fn indent_at(&self, level: usize) -> String {
        " ".repeat(self.opts.indent * level)
    }

    /// Indentation for continuation attribute lines inside a multi-line tag.
    /// Aligns to the column after `<tagname `.
    fn continuation_indent(&self, tag_name: &str) -> String {
        " ".repeat(self.opts.indent * self.level + 1 + tag_name.len() + 1)
    }
}

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

    // Pre-build keyword sets from config
    let indent_kws = indent_keywords(opts);
    let unindent_kws = unindent_keywords(opts);
    let unindent_line_kws = unindent_line_keywords(opts);
    let no_change_kws = no_change_keywords(opts);

    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() {
            let cont_indent = state.continuation_indent(tag_name);
            if html_open_tag_closes_here(trimmed) {
                // This line has the closing `>` — tag is fully open.
                state.multi_line_tag = None;
                out.push_str(&cont_indent);
                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).
                out.push_str(&cont_indent);
                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 {
                        out.push_str(&state.indent());
                    }
                    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;
            out.push_str(&state.indent());
            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);
                out.push_str(&state.indent());
                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 closing tag (`{% end* %}`) → unindent before printing
        if let Some(kw) = parse_template_keyword(trimmed) {
            if unindent_kws.contains(&kw.as_str().to_string()) {
                state.level = state.level.saturating_sub(1);
                out.push_str(&state.indent());
                out.push_str(trimmed);
                out.push('\n');
                continue;
            }

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

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

            // 5. Indent-opening template tag
            if indent_kws.contains(&kw.as_str().to_string()) {
                out.push_str(&state.indent());
                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 {
                    out.push_str(&state.indent());
                    out.push_str(trimmed);
                    out.push('\n');
                    continue;
                }

                // Format attributes if needed
                let formatted = format_attributes(trimmed, state.level, opts);
                out.push_str(&state.indent());
                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) {
            out.push_str(&state.indent());
            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);
        out.push_str(&state.indent());
        out.push_str(&formatted);
        out.push('\n');
    }

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

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

fn indent_keywords(opts: &FormatOptions) -> Vec<String> {
    let mut kws: Vec<String> = vec![
        "if".into(),
        "for".into(),
        "macro".into(),
        "block".into(),
        "filter".into(),
        "with".into(),
        "raw".into(),
    ];
    for b in &opts.custom_blocks {
        kws.push(b.clone());
    }
    kws
}

fn unindent_keywords(opts: &FormatOptions) -> Vec<String> {
    let mut kws: Vec<String> = vec![
        "endif".into(),
        "endfor".into(),
        "endmacro".into(),
        "endblock".into(),
        "endfilter".into(),
        "endwith".into(),
        "endraw".into(),
    ];
    for b in &opts.custom_blocks {
        kws.push(format!("end{}", b));
    }
    kws
}

fn unindent_line_keywords(opts: &FormatOptions) -> Vec<String> {
    let mut kws: Vec<String> = vec!["else".into(), "else if".into()];
    for b in &opts.custom_blocks_unindent_line {
        kws.push(b.clone());
    }
    kws
}

fn no_change_keywords(opts: &FormatOptions) -> Vec<String> {
    let mut kws: Vec<String> = vec![
        "let".into(),
        "import".into(),
        "include".into(),
        "extends".into(),
    ];
    for b in &opts.ignore_blocks {
        kws.push(b.clone());
        kws.push(format!("end{}", b));
    }
    kws
}

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

/// If line starts with `</tag`, return `tag` (lowercased).
fn parse_html_close_tag(line: &str) -> Option<String> {
    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].to_lowercase())
}

/// 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<String> {
    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".to_string());
    }
    let kw: String = inner
        .split_whitespace()
        .next()
        .unwrap_or("")
        .trim_end_matches(['-', '+', '~'])
        .to_string();
    if kw.is_empty() {
        None
    } else {
        Some(kw)
    }
}

/// Returns `(tag_name, is_self_closing, has_matching_close_on_same_line)`.
fn parse_html_open_tag(line: &str) -> Option<(String, 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].to_lowercase();

    // 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 close_tag = format!("</{}", tag);
    let has_close = after_open.to_lowercase().contains(&close_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_lowercase();
    // 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 ─────────────────────────────────────────────────────

/// If the line is an HTML open tag whose attributes are long, break them.
fn format_attributes(line: &str, level: usize, opts: &FormatOptions) -> String {
    maybe_format_attributes(line, level, opts)
}

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

    // Find tag name
    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];

    // Find where attributes start (after tag name + whitespace)
    let after_name = &s[1 + name_end..];
    if !after_name.starts_with(|c: char| c.is_whitespace()) {
        return s.to_string();
    }

    // Find where the open tag ends (the `>` or `/>`) and what follows (content).
    // Do this BEFORE the length check so we measure only the tag's attributes,
    // not any inline content that comes after `>` (e.g. `<a href="x">text</a>`).
    let (tag_only, after_close) = split_tag_from_content(s);

    // Check if the attributes-only portion exceeds max_attribute_length.
    // Mirrors djLint: `if len(attributes) < config.max_attribute_length: return`.
    let attrs_start = 1 + name_end; // after `<tagname`
    let attrs_str = if attrs_start < tag_only.len() {
        &tag_only[attrs_start..]
    } else {
        ""
    };
    let attrs_only_len = attrs_str.trim_end_matches(['>', '/']).len();
    if attrs_only_len < opts.max_attribute_length {
        return s.to_string();
    }

    // Parse attributes from just the tag
    let attrs = parse_attributes(tag_only);
    if attrs.len() < 2 {
        return s.to_string();
    }

    // Spacing: align subsequent attributes under the first attribute column.
    // Column = indent * level + `<tagname ` width
    let align_spaces = " ".repeat(opts.indent * level + 1 + tag_name.len() + 1);

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

    let mut out_lines = Vec::new();
    for (i, attr) in attrs.iter().enumerate() {
        if i == 0 {
            out_lines.push(format!("<{} {}", tag_name, attr));
        } else {
            out_lines.push(format!("{}{}", align_spaces, attr));
        }
    }

    // Last attribute line gets the close bracket + any inline content
    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)
}

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
}