Skip to content

Visual Studio Code, rebuilt in Rust

Rust
2.4 KB
Raw Blame
// The directive data and the decisions of the completion and hover providers, without the vscode API (lib.test.ts).
const directives = require('./directives.json');

const contextNames = { s: 'server config', v: 'virtual host', d: 'directory', h: '.htaccess', p: 'proxy section' };

const byName = new Map();
for (const directive of directives) {
	const key = directive.name.toLowerCase();
	byName.set(key, [...(byName.get(key) ?? []), directive]);
}

// The completions for the text before the cursor: directive names at the start of a line, sections after `<`, the
// section name a `</` closes. `word` is the part already typed, which the completion replaces.
function completions(linePrefix) {
	const match = /^\s*(<\/?)?([A-Za-z0-9_]*)$/.exec(linePrefix);
	if (!match) {
		return undefined;
	}
	const [, tag = '', word] = match;
	const items = [];
	for (const directive of directives) {
		if (directive.section !== (tag !== '')) {
			continue;
		}
		items.push({ label: directive.name, snippet: snippet(directive, tag), detail: directive.module, documentation: documentation(directive) });
	}
	return { word, items };
}

// The hover of a directive name at the start of a line, with or without `<` or `</`.
function hover(lineText, start, end) {
	if (!/^\s*<?\/?$/.test(lineText.slice(0, start))) {
		return undefined;
	}
	const found = byName.get(lineText.slice(start, end).toLowerCase());
	return found?.map(documentation).join('\n\n---\n\n');
}

function documentation(directive) {
	const lines = ['```apacheconf', directive.syntax, '```', '', directive.description, ''];
	if (directive.default) {
		lines.push(`Default: \`${directive.default}\`  `);
	}
	lines.push(`Context: ${[...directive.context].map(letter => contextNames[letter]).join(', ')}  `);
	lines.push(`Module: [${directive.module}](https://httpd.apache.org/docs/2.4/mod/${directive.module}.html#${directive.anchor})`);
	return lines.join('\n');
}

function snippet(directive, tag) {
	if (tag === '</') {
		return `${directive.name}>`;
	}
	if (tag === '') {
		return `${directive.name} `;
	}
	// `<Directory directory-path> ... </Directory>` gives `directory-path`.
	const parameters = directive.syntax.slice(directive.name.length + 1).split('>')[0].trim();
	const open = parameters ? `${directive.name} \${1:${parameters}}>` : `${directive.name}>`;
	return `${open}\n\t$0\n</${directive.name}>`;
}

module.exports = { completions, hover };