Skip to content

Commit

Permalink
feat: add support for files.insertFinalNewline during formatOnSave
Browse files Browse the repository at this point in the history
When the `files.insertFinalNewline` property is set to true,
formatOnSave() will ensure that the file ends with a newline character
instead of always removing a final empty line.

Contributed on behalf of STMicroelectronics

Signed-off-by: Olaf Lessenich <[email protected]>
  • Loading branch information
xai committed Jun 3, 2024
1 parent 0941a8f commit 3f9ef10
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/filesystem/src/browser/filesystem-preferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ export const filesystemPreferenceSchema: PreferenceSchema = {
description: nls.localizeByDefault('When enabled, will trim trailing whitespace when saving a file.'),
scope: 'language-overridable'
},
'files.insertFinalNewline': {
type: 'boolean',
default: false,
description: nls.localizeByDefault('When enabled, insert a final new line at the end of the file when saving it.'),
scope: 'language-overridable'
},
'files.maxConcurrentUploads': {
type: 'integer',
default: 1,
Expand All @@ -117,6 +123,7 @@ export interface FileSystemConfiguration {
'files.participants.timeout': number
'files.maxFileSizeMB': number
'files.trimTrailingWhitespace': boolean
'files.insertFinalNewline': boolean
'files.maxConcurrentUploads': number
}

Expand Down
33 changes: 33 additions & 0 deletions packages/monaco/src/browser/monaco-editor-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,10 @@ export class MonacoEditorProvider {
if (shouldRemoveWhiteSpace) {
await editor.runAction('editor.action.trimTrailingWhitespace');
}
const insertFinalNewline = this.filePreferences.get({ preferenceName: 'files.insertFinalNewline', overrideIdentifier }, undefined, uri);
if (insertFinalNewline) {
this.insertFinalNewline(editor);
}
return [];
}

Expand Down Expand Up @@ -452,4 +456,33 @@ export class MonacoEditorProvider {
)
) as MonacoDiffEditor;
}

protected insertFinalNewline(editor: MonacoEditor): void {
const model = editor.document && editor.document.textEditorModel;
if (!model) {
return;
}

const lines = model?.getLineCount();
if (lines === 0) {
return;
}

const lastLine = model?.getLineContent(lines);
if (lastLine.trim() === '') {
return;
}

const lastLineMaxColumn = model?.getLineMaxColumn(lines);
const range = {
startLineNumber: lines,
startColumn: lastLineMaxColumn,
endLineNumber: lines,
endColumn: lastLineMaxColumn
};
model?.applyEdits([{
range,
text: model?.getEOL()
}]);
}
}

0 comments on commit 3f9ef10

Please sign in to comment.