All files / languages/xml/providers xml-rename-provider.ts

100% Statements 107/107
98.36% Branches 60/61
100% Functions 7/7
100% Lines 107/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                        22x       6x   6x 1x     5x     5x   5x 2x   2x 1x     1x   1x       3x   3x 2x   2x 1x     1x   1x     1x                   8x   8x 13x       13x 14x 14x   14x 14x   14x   14x       8x                   6x   6x 1x     5x 5x   5x 2x   2x 1x 1x   1x   1x 1x   1x       3x   3x 1x   1x 1x 1x   1x       2x   2x                     4x   4x 1x     3x   3x         3x         3x         3x         3x                   10x   10x 1x     9x 9x     9x 2x   2x 1x 1x   1x       8x   8x 3x       5x   5x 1x 1x   1x             4x 4x   4x   1x     3x   2x   2x 1x     1x 1x   1x           1x                       5x 5x   5x 1x     4x   4x         4x   4x 2x         2x           4x 1x           4x    
import * as vscode from 'vscode';
import { Uri } from '@faubulous/mentor-rdf';
import { container } from 'tsyringe';
import { ServiceToken } from '@src/services/tokens';
import { IDocumentContextService } from '@src/services/document';
import { XmlDocument } from '@src/languages/xml/xml-document';
import { XmlFeatureProvider } from '@src/languages/xml/xml-feature-provider';
 
/**
 * Interface for regular expression based text replacements.
 */
interface TextReplacement {
	/**
	 * The regular expression to match the text to be replaced.
	 */
	fromExpression: RegExp;
 
	/**
	 * The replacement text.
	 */
	toValue: string;
}
 
/**
 * Provides renaming for URIs, resources labels and prefixes.
 */
export class XmlRenameProvider extends XmlFeatureProvider implements vscode.RenameProvider {
	private get contextService() {
		return container.resolve<IDocumentContextService>(ServiceToken.DocumentContextService);
	}
 
	public provideRenameEdits(document: vscode.TextDocument, position: vscode.Position, newName: string): vscode.ProviderResult<vscode.WorkspaceEdit> {
		const context = this.contextService.getDocumentContext(document, XmlDocument);
 
		if (!context) {
			return undefined;
		}
 
		const edits = new vscode.WorkspaceEdit();
 
		// Handle rename of local names. Either of prefixed names or in IRIs.
		const nameRange = this._getLocalNameEditRange(document, position);
 
		if (nameRange && nameRange.contains(position)) {
			const iri = context.getIriAtPosition(position);
 
			if (!iri) {
				return undefined;
			}
 
			const replacements = this._getLocalNameTextReplacements(context, iri, newName);
 
			return this.getWorkspaceEdits(document, replacements);
		}
 
		// Handle rename of prefixes and prefix definitions.
		const prefixRange = this._getPrefixEditRange(document, position);
 
		if (prefixRange && prefixRange.contains(position)) {
			const prefix = document.getText(prefixRange);
 
			if (!context.namespaces[prefix]) {
				return undefined;
			}
 
			const replacements = this._getPrefixTextReplacements(context, prefix, newName);
 
			return this.getWorkspaceEdits(document, replacements);
		}
 
		return edits;
	}
 
	/**
	 * Get the workspace edits for the given text replacements.
	 * @param document The document to be edited.
	 * @param replacements The replacements to apply.
	 * @returns A workspace edit containing the replacements.
	 */
	getWorkspaceEdits(document: vscode.TextDocument, replacements: TextReplacement[]): vscode.WorkspaceEdit {
		const edits = new vscode.WorkspaceEdit();
 
		for (const replacement of replacements) {
			const documentText = document.getText();
 
			let match: RegExpExecArray | null;
 
			while ((match = replacement.fromExpression.exec(documentText)) !== null) {
				const matchIndex = match.index;
				const matchLength = match[0].length;
 
				const start = document.positionAt(matchIndex);
				const end = document.positionAt(matchIndex + matchLength);
 
				const range = new vscode.Range(start, end);
 
				edits.replace(document.uri, range, replacement.toValue);
			}
		}
 
		return edits;
	}
 
	/**
	 * Get the range of a prefix to be edited in the XML document at the given position.
	 * @param document The XML document.
	 * @param position The position where to look for the prefix.
	 * @returns The range of the prefix to be edited, or `undefined` if not found.
	 */
	private _getPrefixEditRange(document: vscode.TextDocument, position: vscode.Position): vscode.Range | undefined {
		const context = this.contextService.getDocumentContext(document, XmlDocument);
 
		if (!context) {
			return undefined;
		}
 
		const line = document.lineAt(position.line).text;
		const prefixedNameRange = context.getPrefixedNameRangeAtPosition(line, position);
 
		if (prefixedNameRange) {
			const prefixedName = document.getText(prefixedNameRange);
 
			if (prefixedName.startsWith('xmlns:')) {
				const start = prefixedNameRange.start.translate(0, 6);
				const end = prefixedNameRange.end;
 
				return new vscode.Range(start, end);
			} else {
				const start = prefixedNameRange.start;
				const end = prefixedNameRange.start.translate(0, prefixedName.indexOf(":"));
 
				return new vscode.Range(start, end);
			}
		}
 
		const attributeValueRange = context.getAttributeValueRangeAtPosition(line, position);
 
		if (attributeValueRange) {
			const attributeValue = document.getText(attributeValueRange);
 
			Eif (attributeValue.startsWith('&')) {
				const start = attributeValueRange.start.translate(0, 1);
				const end = attributeValueRange.end.translate(0, attributeValue.indexOf(";"));
 
				return new vscode.Range(start, end);
			}
		}
 
		const entityRange = context.getEntityRangeAtPosition(line, position);
 
		return entityRange;
	}
 
	/**
	 * Get the text replacements for a prefix in the XML document.
	 * @param context The XML document context.
	 * @param prefix The prefix to be replaced.
	 * @param newPrefix The new prefix to replace with.
	 * @returns An array of text replacements.
	 */
	private _getPrefixTextReplacements(context: XmlDocument, prefix: string, newPrefix: string): TextReplacement[] {
		const namespaceIri = context.namespaces[prefix];
 
		if (!namespaceIri) {
			return [];
		}
 
		const result: TextReplacement[] = [];
 
		result.push({
			fromExpression: new RegExp(`xmlns:${prefix}`, 'g'),
			toValue: `xmlns:${newPrefix}`
		});
 
		result.push({
			fromExpression: new RegExp(`${prefix}:`, 'g'),
			toValue: `${newPrefix}:`
		});
 
		result.push({
			fromExpression: new RegExp(`ENTITY ${prefix}`, 'g'),
			toValue: `ENTITY ${newPrefix}`
		});
 
		result.push({
			fromExpression: new RegExp(`&${prefix};`, 'g'),
			toValue: `&${newPrefix};`
		});
 
		return result;
	}
 
	/**
	 * Get the range of a local name to be edited in the XML document at the given position.
	 * @param document The XML document.
	 * @param position The position where to look for the local name.
	 * @returns The range of the local name to be edited, or `undefined` if not found.
	 */
	private _getLocalNameEditRange(document: vscode.TextDocument, position: vscode.Position): vscode.Range | undefined {
		const context = this.contextService.getDocumentContext(document, XmlDocument);
 
		if (!context) {
			return undefined;
		}
 
		const line = document.lineAt(position.line).text;
		const prefixedNameRange = context.getPrefixedNameRangeAtPosition(line, position);
 
		// Match XML prefixed attribute names (e.g. "rdf:about") which cannot occur inside attribute values.
		if (prefixedNameRange) {
			const prefixedName = document.getText(prefixedNameRange);
 
			if (!prefixedName.startsWith('xmlns:') && !prefixedName.startsWith('xml:')) {
				const start = prefixedNameRange.start.translate(0, prefixedName.indexOf(":") + 1);
				const end = prefixedNameRange.end;
 
				return new vscode.Range(start, end);
			}
		}
 
		const attributeValueRange = context.getAttributeValueRangeAtPosition(line, position);
 
		if (!attributeValueRange) {
			return undefined;
		}
 
		// Match entity references (e.g. "&ex;") inside attribute values.
		const attributeValue = document.getText(attributeValueRange);
 
		if (attributeValue.trim().startsWith('&')) {
			const startColumn = attributeValueRange.start.character + attributeValue.indexOf(";") + 1;
			const endColumn = attributeValueRange.start.character + attributeValue.length;
 
			return new vscode.Range(
				new vscode.Position(position.line, startColumn),
				new vscode.Position(position.line, endColumn)
			);
		}
 
		// Match local names (e.g. "Example") inside attribute values that must be resolved using the document base IRI.
		const attributeNameRange = context.getAttributeNameRangeNearPosition(line, position);
		const attributeName = document.getText(attributeNameRange);
 
		if (attributeName !== 'rdf:about' && attributeName !== 'rdf:resource' && attributeName !== 'rdf:datatype') {
			// We only support renaming of rdf:about, rdf:resource and rdf:datatype as these must be IRIs or local names.
			return undefined;
		}
 
		if (attributeValue.includes(':')) {
			// Attribute values only support 
			const localName = Uri.getLocalPart(attributeValue);
 
			if (!localName || localName.length === 0) {
				return undefined;
			}
 
			const startColumn = line.lastIndexOf(localName);
			const endColumn = line.lastIndexOf(localName) + localName.length;
 
			return new vscode.Range(
				new vscode.Position(position.line, startColumn),
				new vscode.Position(position.line, endColumn)
			);
		} else {
			// Local names which need to be resolved using the document base IRI.
			return attributeValueRange;
		}
	}
 
	/**
	 * Get the text replacements for a local name in the XML document.
	 * @param context The XML document context.
	 * @param iri The IRI which includes the local name to be replaced.
	 * @param newName The new local name to replace with.
	 * @returns An array of text replacements.
	 */
	private _getLocalNameTextReplacements(context: XmlDocument, iri: string, newName: string): TextReplacement[] {
		const localName = Uri.getLocalPart(iri);
		const namespaceIri = Uri.getNamespaceIri(iri);
 
		if (!iri.includes(':') || namespaceIri.length === 0 || !localName || localName.length === 0) {
			return [];
		}
 
		const result: TextReplacement[] = [];
 
		result.push({
			fromExpression: new RegExp(`${iri}`, 'g'),
			toValue: `${namespaceIri + newName}`
		});
 
		const prefix = context.getPrefixForNamespaceIri(namespaceIri);
 
		if (prefix) {
			result.push({
				fromExpression: new RegExp(`${prefix}:${localName}`, 'g'),
				toValue: `${prefix}:${newName}`
			});
 
			result.push({
				fromExpression: new RegExp(`&${prefix};${localName}`, 'g'),
				toValue: `&${prefix};${newName}`
			});
		}
 
		if (context.baseIri && iri.startsWith(context.baseIri)) {
			result.push({
				fromExpression: new RegExp(`="${localName}"`, 'g'),
				toValue: `="${newName}"`
			});
		}
 
		return result;
	}
}