Skip to content
Open
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
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,45 @@ to the `fortls` location by setting
For more about the Language Server's capabilities please refer to the
[documentation](https://fortls.fortran-lang.org/) of `fortls`.

## Working with External Libraries (MPI, PETSc, HDF5, etc.)

When using external libraries you may see warnings about unknown modules. The extension provides several ways to handle these:

Option 1: Auto-detect Libraries
1. Open Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
2. Run `Fortran: Configure External Libraries`
3. Select "Auto-detect libraries"
4. Choose which detected libraries to configure

Option 2: Manual Configuration
Add to your workspace `.vscode/settings.json`:

```json
{
"fortran.fortls.externalModules": ["mpi", "mpi_f08", "petsc", "hdf5"],
"fortran.fortls.ignoreExternalDiagnostics": true
}
```

Option 3: Disable Specific Diagnostics

```json
{
"fortran.fortls.disableSpecificDiagnostics": ["unknownModule"]
}
```

Option 4: Provide Module Paths

```json
{
"fortran.fortls.externalModulePaths": [
"/usr/lib/x86_64-linux-gnu/openmpi/include",
"/usr/include"
]
}
```

## Linting

Linting allows for compiler error and warning detection while coding
Expand Down
56 changes: 56 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"activationEvents": [
"onLanguage:FortranFreeForm",
"onLanguage:FortranFixedForm",
"onCommand:fortran.configureExternalLibraries",
"onCommand:fortran.analysis.restartLanguageServer",
"onCommand:fortran.analysis.rescanLinter",
"onCommand:fortran.analysis.cleanLinterDiagnostics",
Expand Down Expand Up @@ -542,6 +543,49 @@
"markdownDescription": "Disable the Language Server. If true, it will limit the extension's functionality substantially. **Should be avoided!**",
"order": 1300
}
,
"fortran.fortls.disableSpecificDiagnostics": {
"type": "array",
"items": {
"type": "string",
"enum": [
"unknownModule",
"unknownType",
"multipleDefinition",
"variableMasking",
"missingArgument",
"unclosedBlock",
"invalidNesting"
]
},
"default": [],
"markdownDescription": "Disable specific diagnostic types from fortls. Useful when working with external libraries. Options:\n- `unknownModule`: Unknown modules in USE statements\n- `unknownType`: Unknown user-defined types\n- `multipleDefinition`: Multiple definitions with same name\n- `variableMasking`: Variable masks parent scope\n- `missingArgument`: Missing subroutine/function arguments\n- `unclosedBlock`: Unclosed blocks/scopes\n- `invalidNesting`: Invalid scope nesting",
"order": 1301
},
"fortran.fortls.externalModules": {
"type": "array",
"items": {
"type": "string"
},
"default": [],
"markdownDescription": "List of external module names to treat as valid (e.g., [\"mpi\", \"petsc\", \"hdf5\"]). Suppresses 'unknown module' warnings for these modules. Case-insensitive.",
"order": 1302
},
"fortran.fortls.externalModulePaths": {
"type": "array",
"items": {
"type": "string"
},
"default": [],
"markdownDescription": "Paths to directories containing external library .mod files. Supports glob patterns and variables like ${workspaceFolder}. Example: /usr/lib/x86_64-linux-gnu/openmpi/include",
"order": 1303
},
"fortran.fortls.ignoreExternalDiagnostics": {
"type": "boolean",
"default": false,
"markdownDescription": "Suppress all diagnostics for modules/types that cannot be found in the project. Useful when working with external libraries like MPI, PETSc, etc.",
"order": 1304
}
}
},
{
Expand Down Expand Up @@ -659,6 +703,12 @@
"icon": "$(debug-alt)",
"title": "Debug Fortran File"
}
,
{
"category": "Fortran",
"command": "fortran.configureExternalLibraries",
"title": "Configure External Libraries"
}
],
"menus": {
"commandPalette": [
Expand All @@ -674,6 +724,12 @@
"title": "Rescan Linter paths",
"when": "!virtualWorkspace && shellExecutionSupported"
},
{
"category": "Fortran",
"command": "fortran.configureExternalLibraries",
"title": "Configure External Libraries",
"when": "!virtualWorkspace && shellExecutionSupported"
},
{
"category": "Fortran",
"command": "fortran.analysis.initLinter",
Expand Down
7 changes: 7 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { WhatsNew } from './commands/commands';
import { FortranCompletionProvider } from './fallback-features/completion-provider';
import { FortranDocumentSymbolProvider } from './fallback-features/document-symbol-provider';
import { FortranHoverProvider } from './fallback-features/hover-provider';
import { configureLibrarySupport } from './features/libraryConfig';
import { FortranFormattingProvider } from './format/provider';
import { FortranLintingProvider } from './lint/provider';
import { FortlsClient } from './lsp/client';
Expand Down Expand Up @@ -109,6 +110,12 @@ export async function activate(context: vscode.ExtensionContext) {
);

context.subscriptions.push(vscode.commands.registerCommand(WhatsNew, showWhatsNew));
// Register external libraries configuration command
const libraryConfigCommand = vscode.commands.registerCommand(
'fortran.configureExternalLibraries',
configureLibrarySupport
);
context.subscriptions.push(libraryConfigCommand);
// Upon the very first initialisation create a file to indicate that the release
// notes have been shown and not show them again.
if (
Expand Down
170 changes: 170 additions & 0 deletions src/features/libraryConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { execSync } from 'child_process';

import * as vscode from 'vscode';

interface LibraryConfig {
name: string;
moduleNames: string[];
detectCommand?: string;
includePaths?: string[];
}

const COMMON_LIBRARIES: LibraryConfig[] = [
{
name: 'OpenMPI',
moduleNames: ['mpi', 'mpi_f08', 'mpi_ext'],
detectCommand: 'mpifort --showme:incdirs',
},
{
name: 'MPICH',
moduleNames: ['mpi', 'mpi_f08'],
detectCommand: 'mpif90 -show | grep -oP "(?<=-I)[^ ]+"',
},
{
name: 'PETSc',
moduleNames: ['petsc', 'petscsnes', 'petscvec', 'petscmat'],
detectCommand: 'pkg-config --variable=includedir PETSc',
},
{
name: 'HDF5',
moduleNames: ['hdf5', 'h5fortran'],
detectCommand: 'h5fc -show | grep -oP "(?<=-I)[^ ]+"',
},
{
name: 'NetCDF',
moduleNames: ['netcdf'],
detectCommand: 'nf-config --includedir',
},
{
name: 'LAPACK',
moduleNames: ['lapack', 'blas'],
},
{
name: 'ScaLAPACK',
moduleNames: ['scalapack'],
},
];

export async function detectLibraries(): Promise<LibraryConfig[]> {
const detected: LibraryConfig[] = [];

for (const lib of COMMON_LIBRARIES) {
if (lib.detectCommand) {
try {
const output = execSync(lib.detectCommand, { encoding: 'utf-8' }).trim();
if (output) {
detected.push({
...lib,
includePaths: output.split('\n').filter(p => p.length > 0),
});
}
} catch (error) {
// Library not installed or command failed
continue;
}
}
}

return detected;
}

export async function configureLibrarySupport(): Promise<void> {
const choice = await vscode.window.showQuickPick(
[
{
label: 'Auto-detect libraries',
description: 'Automatically detect MPI, PETSc, HDF5, etc.',
},
{
label: 'Configure manually',
description: 'Manually specify module names',
},
],
{
placeHolder: 'How would you like to configure external library support?',
}
);

if (!choice) return;

if (choice.label === 'Auto-detect libraries') {
await autoDetectAndConfigure();
} else {
await manualConfiguration();
}
}

async function autoDetectAndConfigure(): Promise<void> {
const detected = await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: 'Detecting Fortran libraries...',
},
async () => await detectLibraries()
);

if (detected.length === 0) {
vscode.window.showInformationMessage(
'No external libraries detected. You can configure them manually.'
);
return;
}

const selected = await vscode.window.showQuickPick(
detected.map(lib => ({
label: lib.name,
description: `Modules: ${lib.moduleNames.join(', ')}`,
picked: true,
lib,
})),
{
canPickMany: true,
placeHolder: 'Select libraries to configure',
}
);

if (!selected || selected.length === 0) return;

const config = vscode.workspace.getConfiguration('fortran.fortls');
const currentModules = config.get<string[]>('externalModules', []);
const currentPaths = config.get<string[]>('externalModulePaths', []);

const newModules = Array.from(
new Set([...currentModules, ...selected.flatMap((s: any) => s.lib.moduleNames)])
);

const newPaths = Array.from(
new Set([...currentPaths, ...selected.flatMap((s: any) => s.lib.includePaths || [])])
);

await config.update('externalModules', newModules, vscode.ConfigurationTarget.Workspace);
await config.update('externalModulePaths', newPaths, vscode.ConfigurationTarget.Workspace);

vscode.window.showInformationMessage(
`Configured ${selected.length} libraries. Added ${newModules.length - currentModules.length} modules.`
);
}

async function manualConfiguration(): Promise<void> {
const modules = await vscode.window.showInputBox({
prompt: 'Enter module names separated by commas (e.g., mpi, petsc, hdf5)',
placeHolder: 'mpi, petsc',
});

if (!modules) return;

const moduleList = modules
.split(',')
.map(m => m.trim().toLowerCase())
.filter(m => m.length > 0);

const config = vscode.workspace.getConfiguration('fortran.fortls');
const current = config.get<string[]>('externalModules', []);
const updated = Array.from(new Set([...current, ...moduleList]));

await config.update('externalModules', updated, vscode.ConfigurationTarget.Workspace);

vscode.window.showInformationMessage(
`Added ${moduleList.length} external modules to configuration.`
);
}
22 changes: 22 additions & 0 deletions src/lsp/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ export class FortlsClient {
);
this.logger.info(`[lsp.client] Language Server arguments: ${args.join(' ')}`);
// Options to control the language client
const conf = workspace.getConfiguration(EXTENSION_ID);
const initializationOptions = {
disable_specific_diagnostics: conf.get<string[]>('fortls.disableSpecificDiagnostics', []),
external_modules: (conf.get<string[]>('fortls.externalModules', []) || []).map(m =>
m.toLowerCase()
),
external_module_paths: conf.get<string[]>('fortls.externalModulePaths', []),
ignore_external_diagnostics: conf.get<boolean>('fortls.ignoreExternalDiagnostics', false),
};

const clientOptions: LanguageClientOptions = {
documentSelector: FortranDocumentSelector(fileRoot),
outputChannel: this.logger.getOutputChannel(),
Expand All @@ -132,6 +142,7 @@ export class FortlsClient {
// Notify the server about file changes to '.fortls files contained in the workspace
// fileEvents: workspace.createFileSystemWatcher('**/.fortls'),
},
initializationOptions,
};
this.client = new LanguageClient(LS_NAME, this.name, serverOptions, clientOptions);
this.client.start();
Expand All @@ -147,6 +158,16 @@ export class FortlsClient {
);
this.logger.info(`[lsp.client] Language Server arguments: ${args.join(' ')}`);
// Options to control the language client
const conf = workspace.getConfiguration(EXTENSION_ID);
const initializationOptions = {
disable_specific_diagnostics: conf.get<string[]>('fortls.disableSpecificDiagnostics', []),
external_modules: (conf.get<string[]>('fortls.externalModules', []) || []).map(m =>
m.toLowerCase()
),
external_module_paths: conf.get<string[]>('fortls.externalModulePaths', []),
ignore_external_diagnostics: conf.get<boolean>('fortls.ignoreExternalDiagnostics', false),
};

const clientOptions: LanguageClientOptions = {
documentSelector: FortranDocumentSelector(folder.uri.fsPath),
workspaceFolder: folder,
Expand All @@ -157,6 +178,7 @@ export class FortlsClient {
// Notify the server about file changes to '.fortls files contained in the workspace
// fileEvents: workspace.createFileSystemWatcher('**/.fortls'),
},
initializationOptions,
};
this.client = new LanguageClient(LS_NAME, this.name, serverOptions, clientOptions);
this.client.start();
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"target": "ES2020",
"outDir": "out",
"lib": ["ES2020"],
"types": ["node", "vscode"],
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
Expand Down