lax-markup 0.2.5

Lax HTML, XML, SVG, and component (Vue, Svelte, Astro) formatter that never reinterprets your markup. Usable as a library or a dprint plugin.
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
use dprint_core::formatting::PrintItems;
use dprint_core::formatting::Signal;
use lax_core::FlowClass;
use lax_core::FlowPrinter;
use lax_core::contains_directive;
use lax_core::push_comment;
use lax_core::push_text;

use std::cell::RefCell;

use super::parser::Node;
use super::tokenizer::is_raw_element;
use crate::configuration::Configuration;
use crate::format_text::ExternalFormatter;

/// Elements that flow with surrounding text. Whitespace around them renders,
/// so content containing them is never restructured. Everything not on this
/// list, including unknown elements and components, is treated as block.
const INLINE_ELEMENTS: &[&str] = &[
  "a", "abbr", "b", "bdi", "bdo", "br", "button", "cite", "code", "data", "dfn", "em", "i", "img", "input", "kbd",
  "label", "mark", "meter", "noscript", "object", "output", "progress", "q", "ruby", "s", "samp", "select", "slot",
  "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr",
];

fn is_inline(name: &str) -> bool {
  INLINE_ELEMENTS.iter().any(|e| e.eq_ignore_ascii_case(name))
}

struct Context<'a> {
  source: &'a str,
  ignore_directive: &'a str,
  line_width: u32,
  external: Option<&'a ExternalFormatter<'a>>,
  external_error: &'a RefCell<Option<anyhow::Error>>,
}

pub fn generate(
  nodes: &[Node],
  source: &str,
  config: &Configuration,
  external: Option<&ExternalFormatter>,
  external_error: &RefCell<Option<anyhow::Error>>,
) -> PrintItems {
  let mut items = PrintItems::new();
  let ctx = Context {
    source,
    ignore_directive: &config.ignore_node_comment_text,
    line_width: config.line_width,
    external,
    external_error,
  };
  if can_restructure(nodes, false, true) {
    gen_structural_children(nodes, &mut items, &ctx);
    items.push_signal(Signal::NewLine);
  } else {
    // a document with top level text flows as written, with `{{ }}`
    // interpolations still formatted
    push_content(&mut items, source.trim_end(), &ctx);
    items.push_signal(Signal::NewLine);
  }
  items
}

fn is_block_node(node: &Node) -> bool {
  match node {
    Node::Element { name, .. } => !is_inline(name),
    Node::Comment { .. } | Node::Verbatim { .. } => true,
    _ => false,
  }
}

/// True when the children can be put one per line without changing what the
/// markup renders as.
///
/// Restructuring writes a newline into every gap: after the open tag,
/// between children, and before the close tag. Whitespace that contains a
/// newline renders as a single space no matter how it is indented, so a gap
/// where the author already had a line break is always safe to renormalize.
/// A gap with no line break is only safe when both of its sides are block
/// level, where whitespace does not render at all. Text pins everything.
///
/// At the document root there are no enclosing tags, so nothing is ever
/// written into the edge gaps and they are always safe.
fn can_restructure(children: &[Node], parent_inline: bool, root: bool) -> bool {
  if children
    .iter()
    .any(|c| matches!(c, Node::Text { .. } | Node::RawText { .. }))
  {
    return false;
  }
  let mut prev_side_block = !parent_inline;
  let mut gap_has_newline = root;
  for child in children {
    if let Node::Whitespace { newlines, .. } = child {
      if *newlines > 0 {
        gap_has_newline = true;
      }
      continue;
    }
    let gap_safe = gap_has_newline || (prev_side_block && is_block_node(child));
    if !gap_safe {
      return false;
    }
    gap_has_newline = false;
    prev_side_block = is_block_node(child);
  }
  root || gap_has_newline || (prev_side_block && !parent_inline)
}

fn gen_structural_children(nodes: &[Node], items: &mut PrintItems, ctx: &Context) {
  let mut first = true;
  let mut pending_blank = false;
  let mut ignore_next = false;
  for node in nodes {
    if let Node::Whitespace { newlines, .. } = node {
      if *newlines >= 2 {
        pending_blank = true;
      }
      continue;
    }
    if !first {
      items.push_signal(Signal::NewLine);
    }
    if pending_blank && !first {
      items.push_signal(Signal::NewLine);
    }
    pending_blank = false;
    first = false;
    let is_comment = matches!(node, Node::Comment { .. });
    if ignore_next && !is_comment {
      let (start, end) = node.span();
      push_text(items, ctx.source[start..end].trim_end());
      ignore_next = false;
      continue;
    }
    if let Node::Comment { text, .. } = node
      && contains_directive(text, ctx.ignore_directive)
    {
      ignore_next = true;
    }
    gen_node(node, items, ctx);
  }
}

fn gen_node(node: &Node, items: &mut PrintItems, ctx: &Context) {
  match node {
    Node::Comment { text, .. } => push_comment(items, ctx.source, text),
    Node::Text { span } => {
      push_content(items, &ctx.source[span.0..span.1], ctx);
    }
    Node::Verbatim { span } | Node::RawText { span } => {
      push_text(items, &ctx.source[span.0..span.1]);
    }
    Node::Whitespace { .. } => {}
    Node::Element {
      name,
      attrs,
      self_closing,
      complete,
      newlines_before_close,
      children,
      closed,
      span,
    } => {
      gen_open_tag(
        name,
        attrs,
        *self_closing,
        *complete,
        *newlines_before_close,
        items,
        ctx,
      );
      if !*complete
        || *self_closing
        || super::parser::VOID_ELEMENTS
          .iter()
          .any(|v| v.eq_ignore_ascii_case(name))
      {
        return;
      }
      let parent_inline = is_inline(name);
      if is_raw_element(name) {
        if let Some(formatted) = format_embedded(name, attrs, children, ctx) {
          if formatted.trim().is_empty() {
            if *closed {
              items.push_string(format!("</{}>", name));
            }
            return;
          }
          // script and style contents sit at the same level as their tag,
          // matching the markup_fmt and dprint default that the Vue and
          // Svelte ecosystems expect
          for line in formatted.trim_end().split('\n') {
            items.push_signal(Signal::NewLine);
            lax_core::push_text_line(items, line.trim_end_matches('\r'));
          }
          if *closed {
            items.push_signal(Signal::NewLine);
            items.push_string(format!("</{}>", name));
          }
          return;
        }
        // raw contents are preserved byte for byte, together with the close
        // tag, so that no whitespace is ever inserted before it; whitespace
        // before `</pre>` would render
        if let Some(first) = children.first() {
          let start = first.span().0;
          let end = if *closed {
            span.1
          } else {
            children.last().unwrap().span().1
          };
          push_text(items, &ctx.source[start..end]);
        } else if *closed {
          items.push_string(format!("</{}>", name));
        }
        return;
      }
      if children.iter().all(|c| matches!(c, Node::Whitespace { .. })) {
        if parent_inline && !children.is_empty() {
          // whitespace inside an inline element renders
          let start = children.first().unwrap().span().0;
          let end = children.last().unwrap().span().1;
          push_text(items, &ctx.source[start..end]);
        }
        // otherwise nothing but whitespace collapses
      } else if can_restructure(children, parent_inline, false) {
        items.push_signal(Signal::StartIndent);
        items.push_signal(Signal::NewLine);
        gen_structural_children(children, items, ctx);
        items.push_signal(Signal::FinishIndent);
        // the newline puts the close tag on its own line; with no close
        // tag in the source there is nothing to put there
        if *closed {
          items.push_signal(Signal::NewLine);
        }
      } else {
        // mixed content is whitespace sensitive and stays as written, except
        // that `{{ }}` interpolations inside it are still formatted
        let start = children.first().map(|c| c.span().0).unwrap();
        let end = children.last().map(|c| c.span().1).unwrap();
        push_content(items, &ctx.source[start..end], ctx);
      }
      if *closed {
        items.push_string(format!("</{}>", name));
      }
    }
  }
}

fn gen_open_tag(
  name: &str,
  attrs: &[super::tokenizer::Attr],
  self_closing: bool,
  complete: bool,
  newlines_before_close: u32,
  items: &mut PrintItems,
  ctx: &Context,
) {
  items.push_string(format!("<{}", name));
  if !attrs.is_empty() {
    let mut flow = FlowPrinter::new(items, false);
    for attr in attrs {
      flow.token(
        items,
        FlowClass::Whitespace {
          newlines: attr.newlines_before,
        },
        |_| {},
      );
      let text = attr.text;
      flow.token(items, FlowClass::Other, |items| push_text(items, text));
    }
    flow.finish(items);
  }
  let _ = ctx;
  if !complete {
    // the file ended inside this tag; nothing is manufactured
    return;
  }
  // when the author put the closing bracket on its own line, keep it there
  // at the tag's indent, the same way attribute newlines are preserved
  if newlines_before_close > 0 {
    items.push_signal(Signal::NewLine);
    if self_closing {
      items.push_string("/>".to_string());
    } else {
      items.push_string(">".to_string());
    }
  } else if self_closing {
    items.push_string(" />".to_string());
  } else {
    items.push_string(">".to_string());
  }
}

/// Pushes a run of source text, formatting any `{{ }}` interpolations in it.
fn push_content(items: &mut PrintItems, text: &str, ctx: &Context) {
  match format_interpolations(text, ctx) {
    Some(formatted) => push_text(items, &formatted),
    None => push_text(items, text),
  }
}

/// Formats the expressions inside `{{ ... }}` interpolations in a run of text,
/// returning the rewritten text when anything changed. Each interpolation
/// interior is handed to the external formatter as an expression; the braces
/// are normalized to `{{ expr }}`. Triple braces (`{{{ }}}`, raw mustache) are
/// left alone, and anything the formatter cannot parse as an expression
/// (template filters, partials, plain text) stays exactly as written, so this
/// never reinterprets non-JavaScript interpolations. Only the expression
/// interior moves; all surrounding text and whitespace is preserved.
fn format_interpolations(text: &str, ctx: &Context) -> Option<String> {
  let external = ctx.external?;
  if !text.contains("{{") {
    return None;
  }
  let b = text.as_bytes();
  let mut out = String::new();
  let mut last = 0;
  let mut i = 0;
  let mut changed = false;
  while i + 1 < b.len() {
    // a `{{` that is not part of a `{{{ }}}` raw block on either side
    let is_open = b[i] == b'{' && b[i + 1] == b'{' && b.get(i + 2) != Some(&b'{') && (i == 0 || b[i - 1] != b'{');
    if is_open
      && let Some(close) = find_double_close(b, i + 2)
      && let Some(expr) = format_interpolation_expr(external, &text[i + 2..close], ctx)
    {
      let replacement = format!("{{{{ {} }}}}", expr);
      // only count as a change when the braces or expression actually move
      if replacement != text[i..close + 2] {
        changed = true;
      }
      out.push_str(&text[last..i]);
      out.push_str(&replacement);
      last = close + 2;
      i = close + 2;
      continue;
    }
    i += 1;
  }
  if !changed {
    return None;
  }
  out.push_str(&text[last..]);
  Some(out)
}

/// Index of the first `}}` at or after `from`, if any.
fn find_double_close(b: &[u8], from: usize) -> Option<usize> {
  let mut j = from;
  while j + 1 < b.len() {
    if b[j] == b'}' && b[j + 1] == b'}' {
      return Some(j);
    }
    j += 1;
  }
  None
}

/// Formats a single interpolation interior as a JavaScript expression. Returns
/// None (keep verbatim) when it is empty, the formatter declines or errors
/// (not valid JS), or the result would span multiple lines, since an
/// interpolation cannot contain a line break. A parse error here is expected
/// for non-JS interpolations and is deliberately not recorded as a failure.
fn format_interpolation_expr(external: &ExternalFormatter, inner: &str, ctx: &Context) -> Option<String> {
  let trimmed = inner.trim();
  if trimmed.is_empty() {
    return None;
  }
  // Mustache/Handlebars control tags (`{{#section}}`, `{{/section}}`,
  // `{{^inverted}}`, `{{> partial}}`, `{{& unescaped}}`, `{{! comment}}`,
  // `{{= =}}`, `{{.}}` and the inheritance sigils `{{< }}`/`{{$ }}`) are not
  // JavaScript expressions, so they must never be handed to the JS formatter
  // and must stay exactly as written. We skip them explicitly rather than
  // relying on the formatter to reject them: a permissive parser happily reads
  // `#section` as a private-name reference and would otherwise space it to
  // `{{ #section }}`, which is wrong and asymmetric with the closing tag.
  if is_mustache_sigil(trimmed.as_bytes()[0]) {
    return None;
  }
  let formatted = match external("ts", trimmed, ctx.line_width) {
    Ok(Some(formatted)) => formatted,
    _ => return None,
  };
  // the external formatter formats a statement; drop the trailing semicolon
  // and surrounding whitespace to recover the expression
  let formatted = formatted.trim().trim_end_matches(';').trim_end();
  if formatted.is_empty() || formatted.contains('\n') {
    return None;
  }
  Some(formatted.to_string())
}

/// Whether `c` is a leading sigil that marks a Mustache/Handlebars control tag
/// rather than a plain interpolated expression. Such tags are left verbatim.
fn is_mustache_sigil(c: u8) -> bool {
  matches!(c, b'#' | b'/' | b'^' | b'>' | b'&' | b'!' | b'=' | b'<' | b'$' | b'.')
}

/// Runs the external formatter over a script or style body. Returns None
/// when there is no external formatter, the element is not embeddable, the
/// formatter declined, or it failed, in which case the error is recorded
/// and the contents stay verbatim for this pass.
fn format_embedded(name: &str, attrs: &[super::tokenizer::Attr], children: &[Node], ctx: &Context) -> Option<String> {
  let external = ctx.external?;
  let kind = if name.eq_ignore_ascii_case("style") {
    "css"
  } else if name.eq_ignore_ascii_case("script") {
    "js"
  } else {
    return None;
  };
  let lang = attr_value(attrs, "lang")
    .or_else(|| attr_value(attrs, "type"))
    .unwrap_or(kind);
  let (start, end) = match (children.first(), children.last()) {
    (Some(first), Some(last)) => (first.span().0, last.span().1),
    _ => return None,
  };
  // hand the content to the external formatter with its common indentation
  // stripped; the formatted result is reindented to the element's level, so
  // stripping first makes the round trip a fixed point even when the inner
  // formatter keeps comment interiors at absolute columns
  let content = dedent(&ctx.source[start..end]);
  match external(lang, &content, ctx.line_width) {
    Ok(result) => result,
    Err(error) => {
      ctx.external_error.borrow_mut().get_or_insert(error);
      None
    }
  }
}

fn attr_value<'a>(attrs: &[super::tokenizer::Attr<'a>], name: &str) -> Option<&'a str> {
  for attr in attrs {
    let text = attr.text;
    let Some(eq) = text.find('=') else { continue };
    if !text[..eq].trim().eq_ignore_ascii_case(name) {
      continue;
    }
    let value = text[eq + 1..].trim();
    let value = value
      .strip_prefix('"')
      .and_then(|v| v.strip_suffix('"'))
      .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
      .unwrap_or(value);
    return Some(value);
  }
  None
}

/// Strips the longest common leading whitespace prefix from every non empty
/// line.
fn dedent(text: &str) -> String {
  let mut common: Option<&str> = None;
  for line in text.split('\n') {
    if line.trim().is_empty() {
      continue;
    }
    let leading = &line[..line.len() - line.trim_start().len()];
    common = Some(match common {
      None => leading,
      Some(prev) => {
        let len = prev
          .as_bytes()
          .iter()
          .zip(leading.as_bytes())
          .take_while(|(a, b)| a == b)
          .count();
        &prev[..len]
      }
    });
  }
  let common = common.unwrap_or("");
  if common.is_empty() {
    return text.to_string();
  }
  text
    .split('\n')
    .map(|line| line.strip_prefix(common).unwrap_or(line))
    .collect::<Vec<_>>()
    .join("\n")
}