Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions Extension/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# C/C++ for Visual Studio Code Changelog

## Unreleased
Comment thread
Colengms marked this conversation as resolved.
Resolved
### Bug Fixes
* Honor later and closer EditorConfig sections, and refresh settings when applicable configs outside workspace folders change.

## Version 1.35.6: November 2, 2026
### New Features
* Add the opt-in `C_Cpp.hoverShowIntegralValuesInHexadecimal` setting to display integral constants in hexadecimal in IntelliSense hovers. [#7281](https://github.com/microsoft/vscode-cpptools/issues/7281)
Expand Down
8 changes: 7 additions & 1 deletion 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 readonly editorConfigWatcher: EditorConfigWatcher = new EditorConfigWatcher(() => this.refreshEditorConfigSettings());
Comment thread
Colengms marked this conversation as resolved.
Resolved
private rootFolder?: vscode.WorkspaceFolder;
private rootRealPath: string;
private workspaceStoragePath: string;
Expand Down Expand Up @@ -1947,6 +1948,10 @@ export class DefaultClient implements Client {
}

private prepareVisibleEditorInfo(editors: readonly vscode.TextEditor[]): { [uri: string]: VisibleEditorInfo } {
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 @@ -4358,6 +4363,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
141 changes: 95 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,73 @@ function getEditorConfig(filePath: string): any {
currentDir = path.dirname(currentDir);
}

// Merge global config with section-based config.
return {
...globalConfig,
...combinedConfig
};
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
};
}
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