- Syntax Highlighting (/syntax): highlight.js tokens rendered with VS Code (Dark/Light Modern, One Dark Pro, Monokai, Dracula, GitHub) and Android Studio (Darcula, Dark, IntelliJ Light) colors; copy as rich text (VS Code clipboard HTML), download RTF, share. Format via Prettier/sql-formatter (lazy-loaded), the JSON printer, or built-in whitespace-only formatters for brace languages, Python and XML. - Markdown: Guide dialog, source next to rendered output, with Insert. - Pastes created by Share count as unread on the Pastebin nav badge. - Paste view: Open in menu built from registry opensPaste tools. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
536 lines
21 KiB
JavaScript
536 lines
21 KiB
JavaScript
// "Format" for the Syntax Highlighting tool.
|
|
//
|
|
// - Prettier (loaded on demand) for JS/TS, CSS/SCSS/Less, HTML, YAML, Markdown, GraphQL
|
|
// - sql-formatter (on demand) for SQL; json-core for JSON (lossless)
|
|
// - our own whitespace-only formatters for brace languages (Kotlin, Java, C-family, Go,
|
|
// Rust, Swift, Dart, PHP, Scala, Groovy), Python and XML. They re-indent, fix spacing and
|
|
// brace placement, and never change anything but whitespace: strings and comments are
|
|
// masked out first (tests check that removing all whitespace gives identical text).
|
|
// - everything else: trailing whitespace and blank-line cleanup only
|
|
import { tokenize } from './highlight-core.js';
|
|
import { parse as parseJson, stringify as stringifyJson } from './json-core.js';
|
|
|
|
const PRETTIER = {
|
|
javascript: ['babel', ['babel', 'estree']],
|
|
typescript: ['babel-ts', ['babel', 'estree']],
|
|
css: ['css', ['postcss']],
|
|
scss: ['scss', ['postcss']],
|
|
less: ['less', ['postcss']],
|
|
markdown: ['markdown', ['markdown']],
|
|
yaml: ['yaml', ['yaml']],
|
|
graphql: ['graphql', ['graphql']],
|
|
html: ['html', ['html', 'babel', 'estree', 'postcss']],
|
|
};
|
|
const BRACE = new Set(['kotlin', 'java', 'c', 'cpp', 'csharp', 'go', 'rust', 'swift', 'dart', 'objectivec', 'php', 'scala', 'groovy', 'protobuf']);
|
|
// XML stays at 4 like Android Studio; HTML (via Prettier) uses 2.
|
|
const TWO_SPACE = new Set(['javascript', 'typescript', 'css', 'scss', 'less', 'html', 'json', 'yaml', 'markdown', 'graphql', 'dart', 'ruby', 'sql']);
|
|
|
|
/** Which engine formats a language, for the UI ("Format (Prettier)"…). */
|
|
export function formatterName(lang, code = '') {
|
|
if (PRETTIER[lang] || (lang === 'xml' && looksLikeHtml(code))) return 'Prettier';
|
|
if (lang === 'sql') return 'sql-formatter';
|
|
if (lang === 'json' || lang === 'xml' || lang === 'python' || BRACE.has(lang)) return 'built-in';
|
|
return 'whitespace cleanup';
|
|
}
|
|
|
|
export function indentUnit(lang, indent) {
|
|
if (indent === 'tab') return '\t';
|
|
if (indent === '2') return ' ';
|
|
if (indent === '4') return ' ';
|
|
if (lang === 'go' || lang === 'makefile') return '\t';
|
|
return TWO_SPACE.has(lang) ? ' ' : ' ';
|
|
}
|
|
|
|
// HTML goes to Prettier; real XML (declaration or namespaces: Android layouts, Mallard, SVG…) to formatXml.
|
|
const looksLikeHtml = (code) => /<!doctype html|<html[\s>]/i.test(code) ||
|
|
(!/<\?xml|\sxmlns[:=]/.test(code) && /<(head|body|div|span|p|script|style|section|main|nav|ul|table)[\s>]/i.test(code));
|
|
|
|
export async function formatCode(code, lang, { indent = 'auto' } = {}) {
|
|
code = code.replace(/\r\n?/g, '\n');
|
|
const unit = indentUnit(lang, indent);
|
|
if (lang === 'xml' && looksLikeHtml(code)) {
|
|
try {
|
|
return await prettierFormat(code, ...PRETTIER.html, unit);
|
|
} catch {
|
|
return formatXml(code, unit); // wasn't HTML after all
|
|
}
|
|
}
|
|
if (PRETTIER[lang]) return prettierFormat(code, ...PRETTIER[lang], unit);
|
|
if (lang === 'json') return stringifyJson(parseJson(code), unit) + '\n';
|
|
if (lang === 'sql') {
|
|
const { format } = await import('../../vendor/sql-formatter.mjs');
|
|
return format(code, { language: 'sql', tabWidth: unit === '\t' ? 4 : unit.length, useTabs: unit === '\t' }) + '\n';
|
|
}
|
|
if (lang === 'xml') return formatXml(code, unit);
|
|
if (lang === 'python') return formatPython(code, unit);
|
|
if (BRACE.has(lang)) return formatBraces(code, lang, unit);
|
|
return cleanupWhitespace(code);
|
|
}
|
|
|
|
async function prettierFormat(code, parser, plugins, unit) {
|
|
const [prettier, ...mods] = await Promise.all([
|
|
import('../../vendor/prettier/standalone.mjs'),
|
|
...plugins.map((p) => import(`../../vendor/prettier/${p}.mjs`)),
|
|
]);
|
|
try {
|
|
return await prettier.format(code, {
|
|
parser,
|
|
plugins: mods.map((m) => m.default || m),
|
|
printWidth: 100,
|
|
tabWidth: unit === '\t' ? 4 : unit.length,
|
|
useTabs: unit === '\t',
|
|
});
|
|
} catch (err) {
|
|
// Prettier's messages include a code frame; the first line is enough for a toast.
|
|
throw new Error(String(err.message).split('\n')[0]);
|
|
}
|
|
}
|
|
|
|
export function cleanupWhitespace(code, maxBlank = 2) {
|
|
const out = [];
|
|
let blanks = 0;
|
|
for (const raw of code.split('\n')) {
|
|
const line = raw.trimEnd();
|
|
if (!line) {
|
|
if (out.length && ++blanks <= maxBlank) out.push('');
|
|
} else {
|
|
blanks = 0;
|
|
out.push(line);
|
|
}
|
|
}
|
|
while (out.length && !out[out.length - 1]) out.pop();
|
|
return out.join('\n') + '\n';
|
|
}
|
|
|
|
// ---------- masking: hide strings and comments behind placeholders ----------
|
|
|
|
const PH_OPEN = '';
|
|
const PH_CLOSE = '';
|
|
const PH_RE = /([0-9a-z]+)/g;
|
|
|
|
function mask(code, lang) {
|
|
const saved = [];
|
|
let out = '';
|
|
let buf = null;
|
|
const flush = () => {
|
|
if (buf == null) return;
|
|
// Keep newlines at the edges of an opaque run outside the placeholder, so lines stay lines.
|
|
const lead = buf.match(/^\n*/)[0];
|
|
const trail = buf.slice(lead.length).match(/\n*$/)[0];
|
|
const core = buf.slice(lead.length, buf.length - trail.length);
|
|
out += lead + (core ? PH_OPEN + (saved.push(core) - 1).toString(36) + PH_CLOSE : '') + trail;
|
|
buf = null;
|
|
};
|
|
for (const t of tokenize(code, lang)) {
|
|
if (t.opaque) buf = (buf ?? '') + t.text;
|
|
else {
|
|
flush();
|
|
out += t.text;
|
|
}
|
|
}
|
|
flush();
|
|
return { text: out, saved };
|
|
}
|
|
|
|
const isLineComment = (s) => /^(\/\/|#)/.test(s);
|
|
const phAt = (line, saved, where) => {
|
|
const m = where === 'end' ? line.match(/([0-9a-z]+)$/) : line.match(/^([0-9a-z]+)/);
|
|
return m ? saved[parseInt(m[1], 36)] : null;
|
|
};
|
|
|
|
function unmask(lines, saved) {
|
|
return lines.map((line) => {
|
|
const indent = line.match(/^[ \t]*/)[0];
|
|
return line.replace(PH_RE, (_, id) => {
|
|
const text = saved[parseInt(id, 36)];
|
|
// Re-align the "*" lines of a block comment with its (possibly re-indented) first line.
|
|
if (text.startsWith('/*') && text.includes('\n')) {
|
|
return text.split('\n').map((l, i) => (i && /^\s*\*/.test(l) ? indent + ' ' + l.trim() : i ? l.trimEnd() : l.trimEnd())).join('\n');
|
|
}
|
|
return text;
|
|
});
|
|
});
|
|
}
|
|
|
|
// ---------- spacing rules (operate on one masked line) ----------
|
|
|
|
const ASSIGN_OPS = ['>>>=', '<<=', '>>=', '<=>', '===', '!==', '**=', '??=', '//=', '==', '!=', '<=', '>=', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '&&', '||', '??', '=>', ':=', '->', '='];
|
|
const OP_CHARS = new Set('=!<>+-*/%&|^?:.~');
|
|
const WORDISH = /[A-Za-z0-9_$)\]'"]/;
|
|
const NOT_BINARY_AFTER = new Set(['return', 'case', 'yield', 'throw', 'in', 'is', 'else', 'await', 'typeof', 'delete', 'void', 'new', 'and', 'or', 'not', 'if', 'elif', 'while', 'print', 'echo']);
|
|
|
|
/**
|
|
* Spaces operators, commas, semicolons and brackets in one masked line.
|
|
* opts: lang; depth0 (Python: '=' unspaced inside brackets); colon (space after ':');
|
|
* arith (space binary + - * / %); pointerLang (leave '*' alone); arrowSpaced ('->');
|
|
* braceSpaceBefore ('){' → ') {'); innerBraceSpace ('{x}' → '{ x }');
|
|
* compare (space < and > comparisons); generics (tell List<T> apart from a < b).
|
|
*/
|
|
function spaceLine(line, opts, startStack = []) {
|
|
const stack = [...startStack];
|
|
const top = () => stack[stack.length - 1];
|
|
let out = '';
|
|
let genericDepth = 0;
|
|
const lastWord = () => (out.trimEnd().match(/[A-Za-z_]\w*$/) || [''])[0];
|
|
const skipSpaces = (i) => {
|
|
while (line[i] === ' ' || line[i] === '\t') i++;
|
|
return i;
|
|
};
|
|
// A binary operator gets a space on both sides, except right after an opening bracket or comma.
|
|
const spaced = (op) => {
|
|
out = out.trimEnd();
|
|
out += !out || /[([{,]$/.test(out) ? `${op} ` : ` ${op} `;
|
|
};
|
|
for (let i = 0; i < line.length; ) {
|
|
const ch = line[i];
|
|
if (ch === PH_OPEN) {
|
|
const j = line.indexOf(PH_CLOSE, i);
|
|
out += line.slice(i, j + 1);
|
|
i = j + 1;
|
|
continue;
|
|
}
|
|
if (ch === ' ' || ch === '\t') {
|
|
if (out && !out.endsWith(' ')) out += ' ';
|
|
i++;
|
|
continue;
|
|
}
|
|
if (ch === '(' || ch === '[') {
|
|
stack.push(ch);
|
|
out += ch;
|
|
i = skipSpaces(i + 1);
|
|
continue;
|
|
}
|
|
if (ch === '{') {
|
|
if (opts.braceSpaceBefore && /[\w)\]>"']$/.test(out) && !(opts.lang === 'go' && /\w$/.test(out))) out += ' ';
|
|
stack.push(ch);
|
|
out += ch;
|
|
const j = skipSpaces(i + 1);
|
|
if (j < line.length && line[j] !== '}' && (opts.innerBraceSpace || j > i + 1)) out += ' ';
|
|
i = j;
|
|
continue;
|
|
}
|
|
if (ch === ')' || ch === ']') {
|
|
if (/[^([]\s+$/.test(out)) out = out.trimEnd();
|
|
stack.pop();
|
|
out += ch;
|
|
i++;
|
|
continue;
|
|
}
|
|
if (ch === '}') {
|
|
if (opts.innerBraceSpace && out.trim() && !/[{\s]$/.test(out)) out += ' ';
|
|
stack.pop();
|
|
out += ch;
|
|
i++;
|
|
continue;
|
|
}
|
|
if (ch === ',' || ch === ';') {
|
|
out = out.trimEnd() + ch;
|
|
i = skipSpaces(i + 1);
|
|
const next = line[i];
|
|
if (next && (!')]};,'.includes(next) || (next === '}' && (opts.innerBraceSpace || line[i - 1] === ' ')))) out += ' ';
|
|
continue;
|
|
}
|
|
// < and > : generics stay tight (List<String>), comparisons get spaces (a < b)
|
|
if (opts.compare && (ch === '<' || ch === '>') && !OP_CHARS.has(line[i - 1] ?? ' ') && !OP_CHARS.has(line[i + 1] ?? ' ')) {
|
|
if (ch === '<' && opts.generics && isGenericOpen(line, i)) {
|
|
genericDepth++;
|
|
out = out.trimEnd() + '<';
|
|
i = skipSpaces(i + 1);
|
|
continue;
|
|
}
|
|
if (ch === '>' && genericDepth > 0) {
|
|
genericDepth--;
|
|
out = out.trimEnd() + '>';
|
|
i++;
|
|
continue;
|
|
}
|
|
spaced(ch);
|
|
i = skipSpaces(i + 1);
|
|
continue;
|
|
}
|
|
if (ch === '>' && genericDepth > 0 && line[i + 1] === '>') {
|
|
// closing nested generics: List<List<Int>>
|
|
while (line[i] === '>' && genericDepth > 0) {
|
|
genericDepth--;
|
|
out += '>';
|
|
i++;
|
|
}
|
|
continue;
|
|
}
|
|
// Assignment, comparison and logical operators. Only at the start of an operator run,
|
|
// and only when the run is exactly a known operator (optionally followed by a unary - ! . ~).
|
|
if (OP_CHARS.has(ch) && !OP_CHARS.has(line[i - 1] ?? ' ')) {
|
|
const op = ASSIGN_OPS.find((o) => line.startsWith(o, i));
|
|
const after = line[i + (op?.length || 0)];
|
|
const usable = op && !(OP_CHARS.has(after ?? ' ') && !'-!.~&*'.includes(after)) && !(genericDepth && op.startsWith('>')) &&
|
|
!(op === '->' && !opts.arrowSpaced) && !(op === '=' && top() === '[' && opts.lang === 'cpp');
|
|
if (usable) {
|
|
if (op === '=' && opts.depth0 && stack.length && top() !== '{') {
|
|
// Python keyword argument / default: no spaces, unless it's annotated (PEP 8).
|
|
const since = out.slice(Math.max(out.lastIndexOf('('), out.lastIndexOf(',')) + 1);
|
|
if (!since.includes(':')) {
|
|
out = out.trimEnd() + '=';
|
|
i = skipSpaces(i + 1);
|
|
continue;
|
|
}
|
|
}
|
|
spaced(op);
|
|
i = skipSpaces(i + op.length);
|
|
continue;
|
|
}
|
|
}
|
|
// Binary arithmetic: only between two operands, never after keywords like return.
|
|
if (opts.arith && '+-*/%'.includes(ch) && !OP_CHARS.has(line[i - 1] ?? ' ') && !OP_CHARS.has(line[i + 1] ?? ' ') &&
|
|
!(opts.pointerLang && ch === '*')) {
|
|
const before = out.trimEnd().slice(-1);
|
|
const j = skipSpaces(i + 1);
|
|
const exponent = (ch === '+' || ch === '-') && /\d[eE]$/.test(out);
|
|
if (before && WORDISH.test(before) && line[j] && /[A-Za-z0-9_$('"]/.test(line[j]) && !exponent && !NOT_BINARY_AFTER.has(lastWord())) {
|
|
spaced(ch);
|
|
i = j;
|
|
continue;
|
|
}
|
|
}
|
|
if (ch === ':' && opts.colon && line[i + 1] !== ':' && line[i - 1] !== ':' && top() !== '[') {
|
|
if (opts.depth0) out = out.trimEnd(); // Python: no space before ':'
|
|
out += ':';
|
|
i = skipSpaces(i + 1);
|
|
if (line[i] && /[A-Za-z0-9_$("'\[{@-]/.test(line[i])) out += ' ';
|
|
continue;
|
|
}
|
|
out += ch;
|
|
i++;
|
|
}
|
|
return { text: out.trimEnd(), stack };
|
|
}
|
|
|
|
// Does the '<' at i open a generic type list? Scan to its matching '>' through type-ish text only.
|
|
function isGenericOpen(line, i) {
|
|
let depth = 0;
|
|
for (let j = i; j < line.length; j++) {
|
|
const c = line[j];
|
|
if (c === '<') depth++;
|
|
else if (c === '>') {
|
|
if (--depth === 0) return j > i + 1;
|
|
} else if (!/[\w\s,.?\[\]*:&@'$]/.test(c) || line.startsWith('&&', j)) return false;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ---------- brace languages ----------
|
|
|
|
const CONTROL_PAREN = /\b(if|for|while|switch|catch|when|using|lock|foreach|synchronized|guard|elif)\(/g;
|
|
const CONTINUATION_START = /^(\.(?!\.)|\?\.|&&|\|\||\?(?![?.])|:(?!:)|\+(?!\+)|-(?![->])|\|>)/;
|
|
const CONTINUATION_END = /((?<![=!<>])=|&&|\|\||(?<!\+)\+|(?<!-)-|->|=>)$/;
|
|
// An unbraced body: `if (x)` / `else` / `for (…)` alone on a line indents the next line.
|
|
const UNBRACED = /^(\}\s*)?(if|else\s+if|for|foreach|while)\b.*\)$|^(\}\s*)?else$/;
|
|
|
|
export function formatBraces(code, lang, unit) {
|
|
const { text, saved } = mask(code, lang);
|
|
const allman = lang === 'csharp';
|
|
const preproc = lang === 'c' || lang === 'cpp' || lang === 'objectivec';
|
|
const caseAtSwitch = lang === 'go' || lang === 'swift';
|
|
const opts = {
|
|
lang,
|
|
braceSpaceBefore: true,
|
|
innerBraceSpace: ['kotlin', 'swift', 'rust', 'scala', 'groovy'].includes(lang),
|
|
colon: ['kotlin', 'swift', 'rust', 'scala', 'go', 'dart'].includes(lang),
|
|
arith: true,
|
|
compare: true,
|
|
generics: true,
|
|
pointerLang: ['c', 'cpp', 'objectivec', 'rust', 'go'].includes(lang),
|
|
arrowSpaced: lang !== 'c' && lang !== 'cpp' && lang !== 'objectivec' && lang !== 'php',
|
|
};
|
|
|
|
// 1. spacing, per line
|
|
let lines = text.split('\n').map((raw) => {
|
|
const t = raw.trim();
|
|
if (!t) return '';
|
|
if (preproc && t.startsWith('#')) return t;
|
|
return spaceLine(t.replace(CONTROL_PAREN, '$1 ('), opts).text.replace(/\}\s*(else|catch|finally)\b/g, '} $1');
|
|
});
|
|
|
|
// 2. brace placement
|
|
const placed = [];
|
|
const lastCode = () => {
|
|
for (let k = placed.length - 1; k >= 0; k--) if (placed[k]) return k;
|
|
return -1;
|
|
};
|
|
for (let line of lines) {
|
|
if (allman) {
|
|
const m = line.match(/^\}\s*(else|catch|finally)\b(.*)$/);
|
|
if (m) {
|
|
placed.push('}');
|
|
line = (m[1] + m[2]).trim();
|
|
}
|
|
if (line.endsWith('{') && line !== '{' && !(preproc && line.startsWith('#'))) {
|
|
placed.push(line.slice(0, -1).trimEnd(), '{');
|
|
continue;
|
|
}
|
|
placed.push(line);
|
|
continue;
|
|
}
|
|
const p = lastCode();
|
|
const prev = p >= 0 ? placed[p] : '';
|
|
const prevEndsInComment = isLineComment(phAt(prev, saved, 'end') || '');
|
|
if (/^\{(\s|$)/.test(line) && p >= 0 && !/[;{}:,]$/.test(prev) && !prevEndsInComment && !(preproc && prev.startsWith('#'))) {
|
|
placed.length = p + 1; // drop blank lines between
|
|
placed[p] = /[([]$/.test(prev) ? prev + line : `${prev} ${line}`;
|
|
continue;
|
|
}
|
|
if (/^(else|catch|finally)\b/.test(line) && prev === '}') {
|
|
placed.length = p + 1;
|
|
placed[p] = `} ${line}`;
|
|
continue;
|
|
}
|
|
placed.push(line);
|
|
}
|
|
|
|
// 3. indentation: brackets left open by a line indent what follows by one level from that line
|
|
// (a line opening several brackets still adds one level); continuation lines add one more.
|
|
const out = [];
|
|
let stack = [];
|
|
let prevCode = '';
|
|
let prevOpened = false;
|
|
for (const line of placed) {
|
|
if (!line) {
|
|
out.push('');
|
|
continue;
|
|
}
|
|
if (preproc && line.startsWith('#')) {
|
|
out.push(line);
|
|
continue;
|
|
}
|
|
const lead = line.match(/^[)\]}]+/)?.[0].length || 0;
|
|
const visible = stack.slice(0, Math.max(0, stack.length - lead));
|
|
let level = visible.length ? visible[visible.length - 1].indent : 0;
|
|
const owner = visible[visible.length - 1];
|
|
const isCase = /^(case\b[^>]*|default\s*):(\s*[0-9a-z]+)?$/.test(line) || /^(case\b.*|default\s*):\s*\S/.test(line) && !/->/.test(line);
|
|
if (isCase && caseAtSwitch) level = Math.max(0, level - 1);
|
|
else if (owner?.inCase && !isCase && !lead) level++;
|
|
if (lang === 'cpp' && /^(public|private|protected)\s*:/.test(line)) level = Math.max(0, level - 1);
|
|
const contStart = CONTINUATION_START.test(line) && !/^-\d/.test(line);
|
|
const contEnd = prevCode && !prevOpened && (CONTINUATION_END.test(prevCode) || UNBRACED.test(prevCode)) && !line.startsWith('{');
|
|
if (!lead && (contStart || contEnd)) level++;
|
|
out.push(unit.repeat(level) + line);
|
|
const depthBefore = stack.length;
|
|
for (const ch of line.replace(PH_RE, '')) {
|
|
if ('([{'.includes(ch)) stack.push({ indent: level + 1, inCase: false });
|
|
else if (')]}'.includes(ch)) stack.pop();
|
|
}
|
|
prevOpened = stack.length > depthBefore;
|
|
if (isCase && owner && !caseAtSwitch) owner.inCase = true;
|
|
prevCode = line.replace(/\s*[0-9a-z]+$/, (m) => (isLineComment(phAt(line, saved, 'end') || '') ? '' : m));
|
|
}
|
|
|
|
// 4. blank lines: none right inside braces, at most one in a row
|
|
const tidy = [];
|
|
for (let k = 0; k < out.length; k++) {
|
|
const line = out[k];
|
|
if (!line) {
|
|
const prev = tidy[tidy.length - 1];
|
|
const next = out.slice(k + 1).find((l) => l);
|
|
if (!tidy.length || prev === '' || /[{(\[]$/.test(prev) || (next && /^\s*[}\])]/.test(next)) || next === undefined) continue;
|
|
}
|
|
tidy.push(line);
|
|
}
|
|
return unmask(tidy, saved).join('\n') + '\n';
|
|
}
|
|
|
|
// ---------- Python ----------
|
|
|
|
export function formatPython(code, unit = ' ') {
|
|
const { text, saved } = mask(code, 'python');
|
|
const opts = { lang: 'python', depth0: true, colon: true, arith: true, arrowSpaced: true, compare: true };
|
|
const out = [];
|
|
const widths = [0]; // indentation widths of the enclosing blocks, as written
|
|
const open = []; // brackets still open from earlier lines: {ch, level}
|
|
let blanks = 0;
|
|
for (const raw of text.split('\n')) {
|
|
const t = raw.trim();
|
|
if (!t) {
|
|
if (out.length && ++blanks <= 2) out.push('');
|
|
continue;
|
|
}
|
|
blanks = 0;
|
|
let level;
|
|
if (open.length) {
|
|
// continuation inside brackets: one level deeper than the line that opened them
|
|
level = open[open.length - 1].level + (/^[)\]}]/.test(t) ? 0 : 1);
|
|
} else {
|
|
const w = raw.match(/^[ \t]*/)[0].replace(/\t/g, ' ').length;
|
|
if (w > widths[widths.length - 1]) widths.push(w);
|
|
else while (widths.length > 1 && w < widths[widths.length - 1]) widths.pop();
|
|
level = widths.length - 1;
|
|
}
|
|
let { text: line } = spaceLine(t.replace(CONTROL_PAREN, '$1 ('), opts, open.map((b) => b.ch));
|
|
// PEP 8: two spaces before an inline comment
|
|
const tail = phAt(line, saved, 'end');
|
|
if (tail && isLineComment(tail) && !line.startsWith(PH_OPEN)) line = line.replace(/ ?([0-9a-z]+)$/, ' $1');
|
|
for (const ch of line.replace(PH_RE, '')) {
|
|
if ('([{'.includes(ch)) open.push({ ch, level });
|
|
else if (')]}'.includes(ch)) open.pop();
|
|
}
|
|
out.push(unit.repeat(level) + line);
|
|
}
|
|
while (out.length && !out[out.length - 1]) out.pop();
|
|
return unmask(out, saved).join('\n') + '\n';
|
|
}
|
|
|
|
// ---------- XML ----------
|
|
|
|
const XML_TOKEN = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE(?:[^>[]|\[[\s\S]*?\])*>|<\/?[A-Za-z_][^>"']*(?:(?:"[^"]*"|'[^']*')[^>"']*)*>|[^<]+|</g;
|
|
|
|
export function formatXml(code, unit = ' ', width = 100) {
|
|
const tokens = code.match(XML_TOKEN) || [];
|
|
if (tokens.includes('<')) throw new Error('Not well-formed XML: stray "<"');
|
|
const out = [];
|
|
let depth = 0;
|
|
const pad = () => unit.repeat(depth);
|
|
for (let i = 0; i < tokens.length; i++) {
|
|
const tok = tokens[i];
|
|
if (!tok.startsWith('<')) {
|
|
const text = tok.trim();
|
|
if (text) for (const l of text.split('\n')) out.push(pad() + l.trim());
|
|
continue;
|
|
}
|
|
if (tok.startsWith('</')) {
|
|
depth = Math.max(0, depth - 1);
|
|
out.push(pad() + tok.replace(/\s+>$/, '>'));
|
|
continue;
|
|
}
|
|
if (tok.startsWith('<!--') || tok.startsWith('<![CDATA[') || tok.startsWith('<?') || /^<!DOCTYPE/i.test(tok)) {
|
|
out.push(pad() + tok);
|
|
continue;
|
|
}
|
|
const m = tok.match(/^<([^\s/>]+)([\s\S]*?)(\s*\/)?>$/);
|
|
const name = m[1];
|
|
const selfClose = !!m[3];
|
|
const attrs = [...m[2].matchAll(/([^\s=]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s"'>]+))?/g)].map((a) => (a[2] ? `${a[1]}=${a[2]}` : a[1]));
|
|
const end = selfClose ? (m[3].startsWith(' ') || attrs.length > 1 ? ' />' : '/>') : '>';
|
|
const oneLine = `<${name}${attrs.map((a) => ' ' + a).join('')}${end}`;
|
|
const androidish = attrs.some((a) => /^(android|app|tools|xmlns):/.test(a));
|
|
let opening;
|
|
if (attrs.length > 1 && (androidish || pad().length + oneLine.length > width)) {
|
|
// Android Studio style: one attribute per line
|
|
opening = [pad() + `<${name}`, ...attrs.map((a, k) => pad() + unit + a + (k === attrs.length - 1 ? end : ''))];
|
|
} else opening = [pad() + oneLine];
|
|
// <a>short text</a> stays on one line
|
|
const text = tokens[i + 1];
|
|
const close = tokens[i + 2];
|
|
if (!selfClose && opening.length === 1 && text && !text.startsWith('<') && close === `</${name}>` && !text.trim().includes('\n')) {
|
|
out.push(opening[0] + text.trim() + close);
|
|
i += 2;
|
|
continue;
|
|
}
|
|
if (!selfClose && tokens[i + 1] === `</${name}>`) {
|
|
opening[opening.length - 1] += `</${name}>`;
|
|
out.push(...opening);
|
|
i += 1;
|
|
continue;
|
|
}
|
|
out.push(...opening);
|
|
if (!selfClose) depth++;
|
|
}
|
|
return out.join('\n') + '\n';
|
|
}
|