Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions Extension/src/LanguageServer/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ import * as configs from './configurations';
import { CopilotCompletionContextFeatures, CopilotCompletionContextProvider } from './copilotCompletionContextProvider';
import { CustomConfigurationProvider1, getCustomConfigProviders, isSameProviderExtensionId } from './customProviders';
import { DataBinding } from './dataBinding';
import { cachedEditorConfigSettings, getEditorConfigSettings } from './editorConfig';
import { cachedEditorConfigSettings, EditorConfigWatcher, getEditorConfigSettings } from './editorConfig';
import { CppSourceStr, clients, configPrefix, initializeIntervalTimer, isWritingCrashCallStack, updateLanguageConfigurations, usesCrashHandler, watchForCrashes } from './extension';
import { IncludeCleanupPreferences, getIncludeCleanupPreferences } from './includeCleanupEditorConfig';
import { InactiveRegion, InactiveRegionStore, getInactiveRegionStartLines } from './inactiveRegions';
Expand Down Expand Up @@ -882,6 +882,7 @@ export class DefaultClient implements Client {
private semanticTokensProviderDisposable: vscode.Disposable | undefined;
private innerConfiguration?: configs.CppProperties;
private rootPathFileWatcher?: vscode.FileSystemWatcher;
private editorConfigWatcher?: EditorConfigWatcher;
private rootFolder?: vscode.WorkspaceFolder;
private rootRealPath: string;
private workspaceStoragePath: string;
Expand Down Expand Up @@ -1947,6 +1948,11 @@ export class DefaultClient implements Client {
}

private prepareVisibleEditorInfo(editors: readonly vscode.TextEditor[]): { [uri: string]: VisibleEditorInfo } {
this.editorConfigWatcher ??= new EditorConfigWatcher(() => this.refreshEditorConfigSettings());
if (this.editorConfigWatcher.update(editors.filter(editor => editor.document.uri.scheme === 'file')
.map(editor => editor.document.uri.fsPath))) {
Comment thread
Colengms marked this conversation as resolved.
Resolved
cachedEditorConfigLookups.clear();
}
const visibileEditorInfo: { [uri: string]: VisibleEditorInfo } = {};
editors.forEach(editor => {
// Use a map, to account for multiple editors for the same file.
Expand Down Expand Up @@ -1975,6 +1981,10 @@ export class DefaultClient implements Client {
// Handles changes to visible files/ranges, changes to current selection/position,
// and changes to the active text editor. Should only be called on the primary client.
public async onDidChangeVisibleTextEditors(editors: readonly vscode.TextEditor[]): Promise<void> {
const defaultClient: Client = clients.getDefaultClient();
if (this !== defaultClient) {
return defaultClient.onDidChangeVisibleTextEditors(editors);
}
const params: DidChangeVisibleTextEditorsParams = {
visibleEditorInfo: this.prepareVisibleEditorInfo(editors)
};
Expand Down Expand Up @@ -2719,10 +2729,11 @@ export class DefaultClient implements Client {
private refreshEditorConfigSettings(): void {
cachedEditorConfigSettings.clear();
cachedEditorConfigLookups.clear();
this.updateActiveDocumentTextOptions();
const defaultClient: Client = clients.getDefaultClient();
defaultClient.updateActiveDocumentTextOptions();

const cppEditors: vscode.TextEditor[] = vscode.window.visibleTextEditors.filter(editor => util.isCpp(editor.document));
void this.onDidChangeVisibleTextEditors(cppEditors).catch(logAndReturn.undefined);
void defaultClient.onDidChangeVisibleTextEditors(cppEditors).catch(logAndReturn.undefined);
}

/**
Expand Down Expand Up @@ -3215,7 +3226,7 @@ export class DefaultClient implements Client {
void SessionState.buildAndDebugIsSourceFile.set(util.isCppOrCFile(editor.document.uri, editor.document.languageId));
void SessionState.buildAndDebugIsFolderOpen.set(util.isFolderOpen(editor.document.uri));
// If using vcFormat, check for a ".editorconfig" file, and apply those text options to the active document.
const settings: CppSettings = new CppSettings(this.RootUri);
const settings: CppSettings = new CppSettings(editor.document.uri);
if (settings.useVcFormat(editor.document)) {
const editorConfigSettings: any = getEditorConfigSettings(editor.document.uri.fsPath);
if (editorConfigSettings.indent_style === "tab") {
Expand Down Expand Up @@ -4358,6 +4369,7 @@ export class DefaultClient implements Client {
}

public dispose(): void {
this.editorConfigWatcher?.dispose();
this.inactiveRegionsDecorations.forEach(currentSet => currentSet.decoration.dispose());
this.inactiveRegionsDecorations.clear();
this.pendingTagParsingCalls.forEach(pendingCall => {
Expand Down
10 changes: 9 additions & 1 deletion Extension/src/LanguageServer/clientCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import * as vscode from 'vscode';
import * as util from '../common';
import * as telemetry from '../telemetry';
import { logAndReturn } from '../Utility/Async/returns';
import * as cpptools from './client';
import { getCustomConfigProviders } from './customProviders';
import { TimeTelemetryCollector } from './timeTelemetryCollector';
Expand Down Expand Up @@ -63,7 +64,8 @@ export class ClientCollection {
this.defaultClient = this.activeClient;
this.languageClients.set(key, this.activeClient);

this.disposables.push(vscode.workspace.onDidChangeWorkspaceFolders(e => this.onDidChangeWorkspaceFolders(e)));
this.disposables.push(vscode.workspace.onDidChangeWorkspaceFolders(e =>
this.onDidChangeWorkspaceFolders(e).catch(logAndReturn.undefined)));
}

public async didChangeActiveEditor(editor?: vscode.TextEditor): Promise<void> {
Expand Down Expand Up @@ -144,6 +146,9 @@ export class ClientCollection {
this.activeClient.activate();
await this.activeClient.didChangeActiveEditor(vscode.window.activeTextEditor);
}

await this.defaultClient.onDidChangeVisibleTextEditors(
vscode.window.visibleTextEditors.filter(editor => util.isCpp(editor.document)));
}

private async onDidChangeWorkspaceFolders(e?: vscode.WorkspaceFoldersChangeEvent): Promise<void> {
Expand Down Expand Up @@ -205,6 +210,9 @@ export class ClientCollection {
this.activeClient.activate();
}
}

await this.defaultClient.onDidChangeVisibleTextEditors(
vscode.window.visibleTextEditors.filter(editor => util.isCpp(editor.document)));
}
}

Expand Down
146 changes: 100 additions & 46 deletions Extension/src/LanguageServer/editorConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,23 @@
import * as fs from 'fs';
import { Minimatch } from 'minimatch';
import * as path from 'path';
import * as vscode from 'vscode';
import * as util from '../common';
import { isWindows } from '../constants';

export const cachedEditorConfigSettings: Map<string, any> = new Map<string, any>();
type EditorConfigSettings = Record<string, string | number | boolean>;

interface EditorConfigSection {
pattern: string;
settings: EditorConfigSettings;
}

interface ParsedEditorConfig {
global: EditorConfigSettings;
sections: EditorConfigSection[];
}

export const cachedEditorConfigSettings: Map<string, EditorConfigSettings> = new Map<string, EditorConfigSettings>();

export function mapIndentationReferenceToEditorConfig(value: string | undefined): string {
if (value !== undefined) {
Expand Down Expand Up @@ -85,10 +98,10 @@ export function matchesSection(pathPrefix: string, filePath: string, section: st
return matcher.match(filePath);
}

function parseEditorConfigContent(content: string): Record<string, any> {
function parseEditorConfigContent(content: string): ParsedEditorConfig {
const lines = content.split(/\r?\n/);
const config: Record<string, any> = {};
let currentSection: string | null = '*'; // Use '*' for sectionless (global) settings.
const config: ParsedEditorConfig = { global: {}, sections: [] };
let currentSettings: EditorConfigSettings = config.global;

lines.forEach(line => {
line = line.trim();
Expand All @@ -99,42 +112,34 @@ function parseEditorConfigContent(content: string): Record<string, any> {
}

if (line.startsWith('[') && line.endsWith(']')) {
// New section (e.g., [*.js])
currentSection = line.slice(1, -1).trim();
config[currentSection] = config[currentSection] || {};
currentSettings = {};
config.sections.push({ pattern: line.slice(1, -1).trim(), settings: currentSettings });
} else {
// Key-value pair (e.g., indent_style = space).
const [key, ...values] = line.split('=');
if (key && values.length > 0) {
const trimmedKey = key.trim();
let value: any = values.join('=').trim();
const trimmedKey = key.trim().toLowerCase();
let value: string | number | boolean = values.join('=').trim();

// Convert boolean-like and numeric values.
if (value === 'true') {
if (value.toLowerCase() === 'true') {
value = true;
} else if (value === 'false') {
} else if (value.toLowerCase() === 'false') {
value = false;
} else if (!isNaN(Number(value))) {
value = Number(value);
}

if (currentSection) {
// Ensure the current section is initialized.
if (!config[currentSection]) {
config[currentSection] = {};
}
config[currentSection][trimmedKey] = value;
}
currentSettings[trimmedKey] = value;
}
}
});

return config;
}

function getEditorConfig(filePath: string): any {
let combinedConfig: any = {};
let globalConfig: any = {};
function getEditorConfig(filePath: string): EditorConfigSettings {
let combinedConfig: EditorConfigSettings = {};
let currentDir: string = path.dirname(filePath);
const rootDir: string = path.parse(currentDir).root;

Expand All @@ -147,33 +152,24 @@ function getEditorConfig(filePath: string): any {
const editorConfigPath: string = path.join(currentDir, '.editorconfig');
if (util.checkFileExistsSync(editorConfigPath)) {
const configFileContent: string = fs.readFileSync(editorConfigPath, 'utf-8');
const configData = parseEditorConfigContent(configFileContent);

// Extract global (sectionless) entries.
if (configData['*']) {
globalConfig = {
...globalConfig,
...configData['*']
};
}
const configData: ParsedEditorConfig = parseEditorConfigContent(configFileContent);
const currentConfig: EditorConfigSettings = { ...configData.global };

let currentDirForwardSlashes: string = currentDir;
if (isWindows) {
currentDirForwardSlashes = currentDir.replace(/\\/g, '/');
}

// Match sections and combine configurations.
Object.keys(configData).forEach((section: string) => {
if (section !== '*' && matchesSection(currentDirForwardSlashes, filePath, section)) {
combinedConfig = {
...configData[section],
...combinedConfig
};
for (const section of configData.sections) {
if (matchesSection(currentDirForwardSlashes, filePath, section.pattern)) {
Object.assign(currentConfig, section.settings);
Comment thread
Colengms marked this conversation as resolved.
Resolved
}
});
}
combinedConfig = { ...currentConfig, ...combinedConfig };

// Check if the current .editorconfig is the root.
if (configData['*']?.root) {
if (configData.global.root === true) {
combinedConfig.root = true;
break; // Stop searching after processing the root = true file.
}
}
Expand All @@ -183,20 +179,78 @@ function getEditorConfig(filePath: string): any {
currentDir = path.dirname(currentDir);
}

// Merge global config with section-based config.
return {
...globalConfig,
...combinedConfig
};
for (const [key, value] of Object.entries(combinedConfig)) {
if (typeof value === 'string' && value.toLowerCase() === 'unset') {
delete combinedConfig[key];
}
}
return combinedConfig;
}

// Look up the appropriate .editorconfig settings for the specified file.
// This is intentionally not async to avoid races due to multiple entrancy.
export function getEditorConfigSettings(fsPath: string): Promise<any> {
let editorConfigSettings: any = cachedEditorConfigSettings.get(fsPath);
export function getEditorConfigSettings(fsPath: string): EditorConfigSettings {
let editorConfigSettings: EditorConfigSettings | undefined = cachedEditorConfigSettings.get(fsPath);
if (!editorConfigSettings) {
editorConfigSettings = getEditorConfig(fsPath);
cachedEditorConfigSettings.set(fsPath, editorConfigSettings);
}
return editorConfigSettings;
}

export class EditorConfigWatcher implements vscode.Disposable {
private readonly watchers: Map<string, vscode.FileSystemWatcher> = new Map<string, vscode.FileSystemWatcher>();

constructor(private readonly onChanged: () => void) { }

public update(filePaths: readonly string[]): boolean {
const directories: Set<string> = new Set<string>();
for (const filePath of filePaths) {
let directory: string = path.dirname(filePath);
for (;;) {
if (!vscode.workspace.getWorkspaceFolder(vscode.Uri.file(directory))) {
directories.add(directory);
}
const parent: string = path.dirname(directory);
if (parent === directory) {
break;
}
directory = parent;
}
}

for (const [directory, watcher] of this.watchers) {
if (!directories.has(directory)) {
watcher.dispose();
this.watchers.delete(directory);
}
}

let addedWatchers: boolean = false;
for (const directory of directories) {
if (this.watchers.has(directory)) {
continue;
}
const watcher: vscode.FileSystemWatcher = vscode.workspace.createFileSystemWatcher(
new vscode.RelativePattern(vscode.Uri.file(directory), '.editorconfig'));
const onChanged = () => {
cachedEditorConfigSettings.clear();
this.onChanged();
};
watcher.onDidCreate(onChanged);
watcher.onDidChange(onChanged);
watcher.onDidDelete(onChanged);
this.watchers.set(directory, watcher);
addedWatchers = true;
}
if (addedWatchers) {
cachedEditorConfigSettings.clear();
}
return addedWatchers;
}

public dispose(): void {
this.watchers.forEach(watcher => watcher.dispose());
this.watchers.clear();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface IncludeCleanupPreferences {
excludedFiles: string;
replacementFiles: string;
requiredFiles: string;
removeUnusedErrorTagType: string;
}

function normalizeSettingKeys(settings: any): Record<string, unknown> {
Expand All @@ -28,6 +29,7 @@ export function getIncludeCleanupPreferences(settings: any): IncludeCleanupPrefe
alternateFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_alternate_files'),
excludedFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_excluded_files'),
replacementFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_replacement_files'),
requiredFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_required_files')
requiredFiles: getStringSetting(normalizedSettings, 'cpp_include_cleanup_required_files'),
removeUnusedErrorTagType: getStringSetting(normalizedSettings, 'cpp_include_cleanup_remove_unused_error_tag_type').toLowerCase() || 'none'
Comment thread
Colengms marked this conversation as resolved.
Resolved
Comment thread
Colengms marked this conversation as resolved.
Resolved
};
}
2 changes: 1 addition & 1 deletion Extension/src/LanguageServer/protocolFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export function createProtocolFilter(): Middleware {
client.takeOwnership(document);
void sendMessage(document);
const cppEditors: vscode.TextEditor[] = vscode.window.visibleTextEditors.filter(e => util.isCpp(e.document));
void client.onDidChangeVisibleTextEditors(cppEditors).catch(logAndReturn.undefined);
void clients.getDefaultClient().onDidChangeVisibleTextEditors(cppEditors).catch(logAndReturn.undefined);
}
}
},
Expand Down
8 changes: 8 additions & 0 deletions Extension/src/nativeStrings.json
Original file line number Diff line number Diff line change
Expand Up @@ -817,5 +817,13 @@
"error_config_arg_requires_path": {
"text": "{0} requires a path.",
"hint": "Error shown when a configuration argument is not followed by a path. {0} is the command-line option name. {Locked=\"{0}\"}"
},
"include_is_not_used": {
"text": "Include is not used",
"hint": "Diagnostic on a C or C++ include directive whose header is unused."
},
"include_is_duplicated": {
"text": "Include is duplicated",
"hint": "Diagnostic on a C or C++ include directive that repeats an earlier include of the same header."
}
}
Loading
Loading