prettier-plugin-wxml.mjs 22.6 KB
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
import { doc } from "prettier";
import prettierPluginMp from "prettier-plugin-mp";

const { group, hardline, indent, join, softline, line, fill } = doc.builders;

const originalPrinter = prettierPluginMp.printers.wxml;

// Helper: indent each line of a string by the given number of spaces
function indentLines(content, indentSize) {
	if (typeof content !== "string") return content;
	const spaces = " ".repeat(indentSize);
	return content
		.split("\n")
		.map((line) => (line ? spaces + line : line))
		.join("\n");
}

// Helper: format WXS JavaScript code
function formatWxsByBabelCompat(jsCode, opts) {
	try {
		// Simple formatting: preserve structure but normalize spacing
		let formatted = jsCode;
		// Normalize line endings
		formatted = formatted.replaceAll("\r\n", "\n");
		// Remove trailing whitespace from each line
		formatted = formatted
			.split("\n")
			.map((line) => line.trimEnd())
			.join("\n");
		return formatted;
	} catch {
		return jsCode; // Return original on error
	}
}

// Helper: enforce quote style for WXS string literals
function enforceWxsStringQuotes(code, useSingle) {
	if (typeof code !== "string") return code;
	// Simple quote normalization for string literals
	// Only replace quotes that are clearly string delimiters
	if (useSingle) {
		// Replace double quotes with single quotes where safe
		return code.replaceAll(/"([^"\n]*)"/g, (match, content) => {
			if (content.includes("'")) return match; // Keep double if contains single
			return `'${content}'`;
		});
	} else {
		// Replace single quotes with double quotes where safe
		return code.replaceAll(/'([^'\n]*)'/g, (match, content) => {
			if (content.includes('"')) return match; // Keep single if contains double
			return `"${content}"`;
		});
	}
}

// Helper: check if mustache content is a simple identifier
function isSimpleMustacheIdentifier(innerLines) {
	if (!Array.isArray(innerLines) || innerLines.length !== 1) return false;
	const line = innerLines[0].trim();
	// Simple identifier: letters, numbers, underscore, dots only
	return /^[a-z_$][\w$.]*$/i.test(line);
}

function printEndTag(path) {
	const node = path.getValue();
	return `</${node.name}>`;
}

function printMisc(path, opts) {
	const node = path.getValue();

	// Handle WXScript nodes
	if (node.type === "WXScript") {
		let result = "";

		// Print start tag manually
		if (node.startTag) {
			const isSelfClosing = !!node.startTag.selfClosing;
			result += `<${node.startTag.name}`;
			if (node.startTag.attributes && node.startTag.attributes.length > 0) {
				for (const attr of node.startTag.attributes) {
					const normalized = attr.value === null ? attr.key : `${attr.key}=${normalizeAttrValueForWxmlQuotes(attr.value, opts)}`;
					result += ` ${normalized}`;
				}
			}
			if (isSelfClosing) {
				result += " />";
				return result; // self-closing: no content, no end tag
			} else {
				result += ">";
			}
		}

		// Print content with proper JavaScript formatting
		if (node.value) {
			result += "\n";
			const jsCode = node.value.trim();
			const indentSize = typeof opts.wxsTabWidth === "number" ? opts.wxsTabWidth : opts.tabWidth || 2;
			// 不再使用 Prettier 路径
			let formatted = formatWxsByBabelCompat(jsCode, opts);
			if (typeof formatted === "string") {
				// Enforce preferred string quote style for simple literals only when formatted
				const useSingle = opts.wxsSingleQuote !== false;
				formatted = enforceWxsStringQuotes(formatted, useSingle);
			} else {
				try {
					const snippet = jsCode.split("\n").slice(0, 5).join("\n");
					console.error("[wxs] Unable to format. First lines:", snippet);
				} catch {}
				// 统一的失败处理:抛出错误以便上层保留原始内容,避免错误输出破坏结构
				throw new Error("Failed to parse/format <wxs> JavaScript");
			}
			const content = formatted.endsWith("\n") ? formatted : `${formatted}\n`;
			result += indentLines(content, indentSize);
		}

		// Print end tag manually
		if (node.endTag) {
			result += `</${node.endTag.name}>`;
		}

		return result;
	}

	throw new Error(`printMisc received unknown node type: ${node.type}. This is a bug in the printer.`);
}

function printCharData(path, opts, print) {
	const node = path.getValue();
	const { value } = node;
	if (!value) return "";

	const isIgnore = opts.htmlWhitespaceSensitivity === "ignore";

	if (value.trim() === "") {
		// In ignore mode, we preserve whitespace-only nodes as a single space
		// to respect source spacing (e.g. "A B").
		// In strict/css mode, or if not inlining, we might drop them elsewhere,
		// but here we return "" to be safe if caller doesn't handle it?
		// Actually, caller (printElement) decides whether to skip this node.
		// If it calls us, and it's ignore mode, we return " ".
		if (isIgnore) return " ";
		return "";
	}

	// Normalize inline template expressions
	let normalized = formatWxmlInterpolations(value, opts);

	if (isIgnore) {
		// Collapse all whitespace sequences (including newlines) to a single space
		// This prevents "ghost" spaces from accumulating and respects "ignore" semantics
		normalized = normalized.replaceAll(/\s+/g, " ");
	}

	return normalized;
}
// Helper: build doc for multi-line mustache printed text, or return null if not applicable
function buildMultiLineMustacheDocFromPrinted(printedText) {
	if (typeof printedText !== "string" || !printedText.includes("\n")) return null;
	const rawLines = printedText.split("\n").map((s) => s.trim());
	if (rawLines[0] !== "{{" || rawLines[rawLines.length - 1] !== "}}") return null;

	const innerLines = rawLines.slice(1, -1);
	const simple = isSimpleMustacheIdentifier(innerLines);

	const contentDoc = [];
	for (let li = 1; li < rawLines.length - 1; li++) {
		contentDoc.push(hardline, rawLines[li]);
	}

	if (simple) {
		// Simple identifier like "title": content aligns with '{{', '}}' at parent indent
		return [indent([hardline, "{{", ...contentDoc]), hardline, "}}", hardline];
	}

	// Complex expression: indent inner content, align '}}' with '{{'
	return [indent([hardline, "{{", indent(contentDoc), hardline, "}}"]), hardline];
}

function printElement(path, opts, print) {
	const node = path.getValue();
	const parts = [];

	// 在最前面定义 attrsArr,这样全函数都可以使用
	const attrsArr = node.startTag && Array.isArray(node.startTag.attributes) ? node.startTag.attributes : [];

	if (node.startTag) {
		// <text> 的处理采用 "早退" 策略,但在此之前仍然会打印开始标签
		parts.push(path.call(print, "startTag"));
	}
	if (node.children && node.children.length > 0) {
		// Decide whether to inline children based on their raw content
		const child0 = node.children[0];
		const isTextNodeType = (n) => n && (n.type === "WXText" || n.type === "WXCharData");
		const isTextLikeNode = (n) => isTextNodeType(n) || n.type === "WXInterpolation";
		const getNodeString = (n) => {
			if (isTextNodeType(n)) return typeof n.value === "string" ? n.value : "";
			if (n.type === "WXInterpolation") return typeof n.rawValue === "string" ? n.rawValue : "";
			return "";
		};
		const getNodeLen = (n) => getNodeString(n).length;

		// 检查标签是否有多个属性,如果有则强制不内联子节点
		const hasMultipleAttrs = attrsArr.length > 1;

		const trimmedLen0 = isTextNodeType(child0) && typeof child0.value === "string" ? child0.value.trim().length : 0;
		const singleTextInline = node.children.length === 1 && isTextNodeType(child0) && trimmedLen0 > 0 && trimmedLen0 < 50 && !child0.value.includes("\n");

		// Determine if children are purely textual/interpolation
		const onlyTextualChildren = node.children.every((n) => isTextLikeNode(n));
		const hasNewline = node.children.some((n) => getNodeString(n).includes("\n"));
		const totalLen = node.children.reduce((acc, n) => acc + getNodeLen(n), 0);
		const hasMeaningful = node.children.some((n) => (isTextNodeType(n) && typeof n.value === "string" && n.value.trim() !== "") || n.type === "WXInterpolation");
		const smallInlineMix = node.children.length <= 3 && onlyTextualChildren && !hasNewline && totalLen < 50 && hasMeaningful;

		const tagName = (node.startTag && node.startTag.name) || (node.endTag && node.endTag.name) || "";
		const lowerName = typeof tagName === "string" ? tagName.toLowerCase() : "";

		// Simplified: treat <block> as always-block, selected tags as prefer-break.
		// Determine shouldInline based on tag type and content
		const isIgnore = opts.htmlWhitespaceSensitivity === "ignore";

		// EARLY RETURN for <text>: verbatim children, no manipulation
		// 说明:<text> 的子节点按原样输出,不进行空白折叠或换行控制;如果存在属性则强制不内联。
		// 在 ignore 模式下,跳过此特殊处理,走通用的内联逻辑
		if (lowerName === "text" && !isIgnore) {
			// 检查 <text> 是否有属性
			const textHasAttrs = attrsArr.length > 0;

			if (textHasAttrs) {
				// 如果有属性,则换行处理子节点
				for (let i = 0; i < node.children.length; i++) {
					const childNode = node.children[i];
					if ((childNode.type === "WXText" || childNode.type === "WXCharData") && typeof childNode.value === "string" && childNode.value.trim() === "") {
						continue; // 跳过空白节点
					}
					const printed = path.call(print, "children", i);
					if (printed && printed !== "") {
						parts.push(printed);
					}
				}
				if (node.endTag) {
					parts.push(path.call(print, "endTag"));
				}
				// 分离内容和结束标签,结束标签单独占一行且不缩进
				const allParts = parts.slice(1); // 跳过开始标签
				if (allParts.length > 0) {
					const endTag = allParts[allParts.length - 1]; // 最后一个是结束标签
					const content = allParts.slice(0, -1); // 前面的是内容
					return group([
						parts[0], // <text ...>
						indent([hardline, ...content]),
						hardline,
						endTag,
					]);
				}
				return group(parts);
			} else {
				// 如果没有属性,按原来的逻辑处理(保持在同一行)
				for (let i = 0; i < node.children.length; i++) {
					const childNode = node.children[i];
					if ((childNode.type === "WXText" || childNode.type === "WXCharData") && typeof childNode.value === "string") {
						parts.push(childNode.value);
					} else if (childNode.type === "WXInterpolation" && typeof childNode.rawValue === "string") {
						parts.push(childNode.rawValue);
					} else {
						parts.push(path.call(print, "children", i));
					}
				}
				if (node.endTag) {
					parts.push(path.call(print, "endTag"));
				}
				return group(parts);
			}
		}

		// Only true block-level tag that must never inline
		const isAlwaysBlock = lowerName === "block";

		// Build prefer-break tags set from options
		const preferBreakTagsInput = typeof opts.wxmlPreferBreakTags === "string" ? opts.wxmlPreferBreakTags : "";
		const preferBreakTags = new Set(
			preferBreakTagsInput
				.split(",")
				.map((s) => s.trim().toLowerCase())
				.filter(Boolean),
		);
		const isPreferBlock = preferBreakTags.has(lowerName);

		// Attributes presence (for simple <text> rule)
		const hasAnyAttrs = attrsArr.length > 0;

		// Simplified: treat <block> as always-block, selected tags as prefer-break.
		// Determine shouldInline based on tag type and content
		// const isIgnore = opts.htmlWhitespaceSensitivity === "ignore"; // moved up
		const shouldInline = ((singleTextInline || smallInlineMix) && !isAlwaysBlock && !isPreferBlock && !hasMultipleAttrs) || (isIgnore && !isAlwaysBlock && !isPreferBlock);

		// Note: <text> is handled via early return above; strict text mode is unused.

		// Now collect printed children according to the decision
		const childrenParts = [];
		const childEntries = [];
		for (let i = 0; i < node.children.length; i++) {
			const childNode = node.children[i];
			const isTextTag = lowerName === "text";
			if (
				(!shouldInline || (isIgnore && !isTextTag)) &&
				(childNode.type === "WXText" || childNode.type === "WXCharData") &&
				typeof childNode.value === "string" &&
				childNode.value.trim() === ""
			) {
				continue; // drop whitespace-only nodes when not inlining or in ignore mode for non-text tags
			}
			// Normal printing for non-<text> tags; <text> has already early-returned above.
			const printed = path.call(print, "children", i);
			if (printed && printed !== "") {
				childrenParts.push(printed);
				childEntries.push({ index: i, node: childNode, printed });
			}
		}

		if (childrenParts.length > 0) {
			if (shouldInline) {
				if (isIgnore) {
					// In ignore mode:
					// 1. For <text>, force it to be a single line (no breaks inside).
					// 2. For other tags, use 'fill' to allow flow layout, but respect breaks.
					if (lowerName === "text") {
						// Force <text> children to be joined without spaces/breaks if possible
						parts.push(childrenParts);
					} else {
						// For other tags (like <view>), we want a "block-like flow" layout:
						// 1. The tag itself breaks (start tag -> newline -> content -> newline -> end tag).
						// 2. But the content flows like text (fill).
						const fillParts = [];
						childrenParts.forEach((part, index) => {
							if (index > 0) fillParts.push(softline);
							fillParts.push(part);
						});
						// Use hardline to force the container to break, but wrap fill() in a group
						// so it tries to stay inline if it fits.
						parts.push(indent([hardline, group(fill(fillParts))]), hardline);
					}
				} else {
					parts.push(...childrenParts);
				}
			} else {
				const childrenWithBreaks = [];
				for (const [i, printed] of childrenParts.entries()) {
					if (i > 0) childrenWithBreaks.push(hardline);
					const entry = childEntries[i];
					// Don't split multi-line text to avoid instability; trust the printed output
					childrenWithBreaks.push(printed);
				}
				{
					// Special-case: multi-line mustache block like "{{\n  title\n}}" inside non-<text> tag
					let didSpecial = false;
					if (lowerName !== "text" && childrenParts.length === 1 && childEntries.length === 1) {
						const entry0 = childEntries[0];
						const printed0 = childrenParts[0];
						const raw0 = getNodeString(entry0.node);
						const isTextNode = entry0 && (entry0.node.type === "WXText" || entry0.node.type === "WXCharData");
						if (isTextNode && typeof printed0 === "string") {
							const mlDoc = buildMultiLineMustacheDocFromPrinted(printed0);
							if (mlDoc) {
								parts.push(...mlDoc);
								didSpecial = true;
							}
						}
					}
					// Normal path
					if (!didSpecial) {
						parts.push(indent([hardline, ...childrenWithBreaks]), hardline);
					}
				}
			}
		}
	}
	if (node.endTag) {
		parts.push(path.call(print, "endTag"));
	}
	return group(parts);
}
function formatInlineJsExpression(expr, opts) {
	if (typeof expr !== "string") return expr;
	// 1) Collapse any newlines (and surrounding spaces) into a single space
	let s = expr.replaceAll(/[ \t]*[\r\n]+[ \t]*/g, " ");
	// 2) Normalize spaces around logical operators
	s = s.replaceAll(/\s*&&\s*/g, " && ").replaceAll(/\s*\|\|\s*/g, " || ");
	// 3) Normalize multiple spaces to single space
	s = s.replaceAll(/ {2,}/g, " ");
	return s.trim();
}
function isPlaceholderLikeValue(value) {
	if (!value) return false;
	let s = String(value);
	// strip surrounding quotes if present
	if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
		s = s.slice(1, -1);
	}
	// detect long runs of the same symbol characters (e.g., ======, ------, ______, ......, ~~~~~~)
	return /([=\-_.~*])\1{5,}/.test(s);
}

function normalizeAttrValueForWxmlQuotes(value, opts) {
	if (!value) return null;
	let attributeValue = String(value);
	// Apply inline expression formatting inside quotes or raw
	const isQuoted = (attributeValue.startsWith('"') && attributeValue.endsWith('"')) || (attributeValue.startsWith("'") && attributeValue.endsWith("'"));
	if (isQuoted) {
		const quote = attributeValue[0];
		let content = attributeValue.slice(1, -1);
		content = formatWxmlInterpolations(content, opts);
		// Decide final quote style based on preference and content
		const preferSingle = !!opts.wxmlSingleQuote;
		if (preferSingle && !content.includes("'")) {
			attributeValue = `'${content}'`;
		} else if (!preferSingle && !content.includes('"')) {
			attributeValue = `"${content}"`;
		} else {
			attributeValue = `${quote}${content}${quote}`;
		}
	} else {
		// Not quoted; first format interpolations then add quotes
		const content = formatWxmlInterpolations(attributeValue, opts);
		attributeValue = opts.wxmlSingleQuote ? `'${content}'` : `"${content}"`;
	}
	return attributeValue;
}
function formatWxmlInterpolations(text, opts) {
	if (typeof text !== "string" || !text.includes("{{")) return text;
	return text.replaceAll(/\{\{([\s\S]*?)\}\}/g, (match) => {
		const inner = match.slice(2, -2); // 去掉 {{ }}
		const trimmedExpr = inner.trim();
		if (!trimmedExpr) return "{{}}";
		const formatted = formatInlineJsExpression(trimmedExpr, opts);
		// Always use single space for consistency
		return `{{ ${formatted} }}`;
	});
}

function printAttribute(path, opts, print) {
	const node = path.getValue();
	const { key, value, rawValue } = node;

	// Handle boolean attributes (no value)
	if (value === null) {
		return key;
	}

	// Normalize attribute value quoting per wxmlSingleQuote
	let attributeValue = rawValue || value;
	if (typeof attributeValue === "string") {
		attributeValue = normalizeAttrValueForWxmlQuotes(attributeValue, opts);
	}

	return `${key}=${attributeValue}`;
}

function printStartTag(path, opts, print) {
	// 从路径中获取当前节点
	const node = path.getValue();
	// 初始化部分数组,包含开始标签的 "<" 和标签名称
	const parts = ["<", node.name];
	// 检查是否存在属性且属性列表不为空
	if (node.attributes && node.attributes.length > 0) {
		// 将每个属性映射为格式化的属性文档字符串
		const attributeDocs = node.attributes.map((attr) => {
			return printAttribute({ getValue: () => attr }, opts, print);
		});

		// 计算所有属性字符串的总长度(包括空格分隔符)
		const attributesLength = attributeDocs.reduce((sum, current) => sum + String(current).length + 1, 0);

		// 获取打印宽度配置,如果没有指定则默认为 80
		const printWidth = typeof opts.wxmlPrintWidth === "number" ? opts.wxmlPrintWidth : opts.printWidth || 80;

		// 计算有多少个属性值看起来像占位符(包含长的重复符号)
		const placeholderCount = (node.attributes || []).filter((attr) => {
			const raw = attr.rawValue || attr.value;
			return isPlaceholderLikeValue(raw);
		}).length;

		// 为占位符属性增加惩罚值,使其更容易触发换行
		const placeholderPenalty = placeholderCount > 0 ? placeholderCount * 10 : 0;

		// 计算标签的大致长度:标签名 + 空格 + 属性长度 + 占位符惩罚
		const approximateLength = node.name.length + 1 + attributesLength + placeholderPenalty;

		// 判断是否应该换行:超过两个属性就换行,或满足其他原始条件
		const shouldBreak = node.attributes.length > 2 || approximateLength > printWidth || placeholderCount >= 2 || (node.selfClosing && node.attributes.length >= 4);

		// 根据换行决策处理属性
		if (shouldBreak) {
			// 如果需要换行,第一个属性保留在开始标签同一行,剩余属性换行显示
			if (attributeDocs.length > 1) {
				// 多个属性:第一个在同一行,后续与第一个对齐
				const firstAttr = attributeDocs[0];
				const restAttrs = attributeDocs.slice(1);
				parts.push(" ", firstAttr);
				// 计算与第一个属性对齐的缩进
				const firstAttrIndent = " ".repeat(node.name.length + 2); // "<" + tagName + space
				const indentedAttributes = [hardline, firstAttrIndent, join([hardline, firstAttrIndent], restAttrs)];
				parts.push(...indentedAttributes);
			} else {
				// 只有一个属性,保留在同一行
				parts.push(" ", attributeDocs[0]);
			}
		} else {
			// 如果不需要换行,在同一行显示所有属性,用空格分隔
			parts.push(" ", join(" ", attributeDocs));
		}
	}

	// 检查标签是否是自闭合标签(如 <view />)
	if (node.selfClosing) {
		// 自闭合标签:添加 " />"
		parts.push(" />");
	} else {
		// 普通标签:添加 ">"
		parts.push(">");
	}
	// 返回所有部分的数组,供上层调用者进一步处理
	return parts;
}

function printDocument(path, opts, print) {
	const node = path.getValue();
	const { body } = node;
	if (!body || body.length === 0) return "";
	const parts = [];
	let lastWasBlock = false; // blocks: element/script/comment
	body.forEach((child, index) => {
		// Drop whitespace-only top-level text nodes to avoid spurious blank lines
		if ((child.type === "WXText" || child.type === "WXCharData") && typeof child.value === "string" && child.value.trim() === "") {
			return;
		}
		const printed = path.call(print, "body", index);
		const isBlock = child.type === "WXElement" || child.type === "WXScript" || child.type === "WXComment";
		if (printed && printed !== "") {
			if (parts.length > 0 && (isBlock || lastWasBlock)) {
				parts.push(hardline);
			}
			parts.push(printed);
		}
		if (printed && printed !== "") {
			lastWasBlock = isBlock;
		}
	});
	if (parts.length > 0) {
		parts.push(hardline);
	}
	return group(parts);
}

function printComment(path) {
	const node = path.getValue();
	return `<!--${node.value}-->`;
}

export default {
	languages: prettierPluginMp.languages,
	parsers: prettierPluginMp.parsers,
	options: prettierPluginMp.options,

	printers: {
		...prettierPluginMp.printers,
		wxml: {
			...originalPrinter,
			print(path, opts, print) {
				const node = path.getValue();
				const ast = path.stack && path.stack[0];
				if (ast && ast.ignoreRanges && node.location) {
					const nodeStart = node.location.startOffset;
					const nodeEnd = node.location.endOffset;
					for (const range of ast.ignoreRanges) {
						if (nodeStart >= range.start && nodeEnd <= range.end) {
							return opts.originalText.slice(nodeStart, nodeEnd);
						}
					}
				}
				switch (node.type) {
					case "Program": {
						return printDocument(path, opts, print);
					}
					case "WXAttribute": {
						return printAttribute(path, opts, print);
					}
					case "WXCharData": {
						return printCharData(path, opts, print);
					}
					case "WXComment": {
						return printComment(path, opts, print);
					}
					case "WXElement": {
						return printElement(path, opts, print);
					}
					case "WXEndTag": {
						return printEndTag(path, opts, print);
					}
					case "WXInterpolation": {
						if (!node.rawValue) {
							throw new Error(`WXInterpolation node missing rawValue. This is a bug in the parser or printer.`);
						}
						return node.rawValue;
					}
					case "WXScript": {
						return printMisc(path, opts, print);
					}
					case "WXStartTag": {
						return printStartTag(path, opts, print);
					}
					case "WXText": {
						return printCharData(path, opts, print);
					}
					default: {
						throw new Error(`Unknown node type: ${node.type}. This is a bug in the printer.`);
					}
				}
			},
		},
	},
};