Skip to content

Commit 987b4de

Browse files
authored
Change the default cell marker (microsoft#7782)
* Change the default cell marker * Fix test failures Fix gather to use new comment Fix formatting on code comments from nls * Fix unit test too * Fix gather to replace #%%
1 parent 218047c commit 987b4de

File tree

15 files changed

+65
-35
lines changed

15 files changed

+65
-35
lines changed

news/2 Fixes/7674.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Change the default cell marker to '# %%' instead of '#%%' to prevent linter errors in python files with markers.
2+
Also added a new setting to change this - 'python.dataScience.defaultCellMarker'.

package.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1562,6 +1562,12 @@
15621562
"description": "Regular expression used to identify code cells. All code until the next match is considered part of this cell. \nDefaults to '^(#\\s*%%|#\\s*\\<codecell\\>|#\\s*In\\[\\d*?\\]|#\\s*In\\[ \\])' if left blank",
15631563
"scope": "resource"
15641564
},
1565+
"python.dataScience.defaultCellMarker": {
1566+
"type": "string",
1567+
"default": "# %%",
1568+
"description": "Cell marker used for delineating a cell in a python file.",
1569+
"scope": "resource"
1570+
},
15651571
"python.dataScience.markdownRegularExpression": {
15661572
"type": "string",
15671573
"default": "^(#\\s*%%\\s*\\[markdown\\]|#\\s*\\<markdowncell\\>)",

package.nls.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@
219219
"DataScience.exportingFormat": "Exporting {0}",
220220
"DataScience.exportCancel": "Cancel",
221221
"Common.canceled": "Canceled",
222-
"DataScience.importChangeDirectoryComment": "#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting",
222+
"DataScience.importChangeDirectoryComment": "{0} Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting",
223223
"DataScience.exportChangeDirectoryComment": "# Change directory to VSCode workspace root so that relative path loads work correctly. Turn this addition off with the DataScience.changeDirOnImportExport setting",
224224
"DataScience.interruptKernelStatus": "Interrupting IPython Kernel",
225225
"DataScience.restartKernelAfterInterruptMessage": "Interrupting the kernel timed out. Do you want to restart the kernel instead? All variables will be lost.",
@@ -341,7 +341,7 @@
341341
"DataScience.jupyterDebuggerInstallPtvsdYes": "Yes",
342342
"DataScience.jupyterDebuggerInstallPtvsdNo": "No",
343343
"DataScience.cellStopOnErrorFormatMessage": "{0} cells were canceled due to an error in the previous cell.",
344-
"DataScience.instructionComments": "# To add a new cell, type '#%%'\n# To add a new markdown cell, type '#%% [markdown]'\n",
344+
"DataScience.instructionComments": "# To add a new cell, type '{0}'\n# To add a new markdown cell, type '{0} [markdown]'\n",
345345
"DataScience.scrollToCellTitleFormatMessage": "Go to [{0}]",
346346
"DataScience.remoteDebuggerNotSupported": "Debugging while attached to a remote server is not currently supported.",
347347
"DataScience.save": "Save notebook",

package.nls.nl.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@
115115
"DataScience.exportingFormat": "Aan het exporteren {0}",
116116
"DataScience.exportCancel": "Annuleren",
117117
"Common.canceled": "Geannuleerd",
118-
"DataScience.importChangeDirectoryComment": "#%% De werkmap van de werkruimte root naar de ipynb-bestandslocatie veranderen. Schakel deze toevoeging uit met de instelling DataScience.changeDirOnImportExport",
118+
"DataScience.importChangeDirectoryComment": "{0} De werkmap van de werkruimte root naar de ipynb-bestandslocatie veranderen. Schakel deze toevoeging uit met de instelling DataScience.changeDirOnImportExport",
119119
"DataScience.exportChangeDirectoryComment": "# De map wijzigen naar de VSCode-werktuimte root zodat de relatieve pad-ladingen correct werken. Schakel deze toevoeging uit met de instelling DataScience.changeDirOnImportExport",
120120
"DataScience.interruptKernelStatus": "IPython-kernel onderbreken",
121121
"DataScience.restartKernelAfterInterruptMessage": "Het onderbreken van de kernel duurde te lang. Wil je de kernel in plaats daarvan herstarten? Alle variabelen zullen verloren gaan.",

snippets/python.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,12 +242,12 @@
242242
},
243243
"add/new/cell": {
244244
"prefix": "add/new/cell",
245-
"body": "#%%",
245+
"body": "# %%",
246246
"description": "Code snippet to add a new cell"
247247
},
248248
"mark/markdown": {
249249
"prefix": "mark/markdown",
250-
"body": "#%% [markdown]",
250+
"body": "# %% [markdown]",
251251
"description": "Code snippet to add a new markdown cell"
252252
}
253253
}

src/client/common/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,7 @@ export interface IDataScienceSettings {
355355
runMagicCommands?: string;
356356
runStartupCommands: string;
357357
debugJustMyCode: boolean;
358+
defaultCellMarker?: string;
358359
}
359360

360361
export const IConfigurationService = Symbol('IConfigurationService');

src/client/common/utils/localize.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ export namespace DataScience {
149149
export const runAllCellsLensCommandTitle = localize('python.command.python.datascience.runallcells.title', 'Run all cells');
150150
export const runAllCellsAboveLensCommandTitle = localize('python.command.python.datascience.runallcellsabove.title', 'Run above');
151151
export const runCellAndAllBelowLensCommandTitle = localize('python.command.python.datascience.runcellandallbelow.title', 'Run Below');
152-
export const importChangeDirectoryComment = localize('DataScience.importChangeDirectoryComment', '#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting');
152+
export const importChangeDirectoryComment = localize('DataScience.importChangeDirectoryComment', '{0} Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting');
153153
export const exportChangeDirectoryComment = localize('DataScience.exportChangeDirectoryComment', '# Change directory to VSCode workspace root so that relative path loads work correctly. Turn this addition off with the DataScience.changeDirOnImportExport setting');
154154

155155
export const restartKernelMessage = localize('DataScience.restartKernelMessage', 'Do you want to restart the Jupter kernel? All variables will be lost.');
@@ -263,7 +263,7 @@ export namespace DataScience {
263263
export const jupyterDebuggerInstallPtvsdNo = localize('DataScience.jupyterDebuggerInstallPtvsdNo', 'No');
264264
export const cellStopOnErrorFormatMessage = localize('DataScience.cellStopOnErrorFormatMessage', '{0} cells were canceled due to an error in the previous cell.');
265265
export const scrollToCellTitleFormatMessage = localize('DataScience.scrollToCellTitleFormatMessage', 'Go to [{0}]');
266-
export const instructionComments = localize('DataScience.instructionComments', '# To add a new cell, type "#%%"\n# To add a new markdown cell, type "#%% [markdown]"\n');
266+
export const instructionComments = localize('DataScience.instructionComments', '# To add a new cell, type "{0}"\n# To add a new markdown cell, type "{0} [markdown]"\n');
267267
export const invalidNotebookFileError = localize('DataScience.invalidNotebookFileError', 'Notebook is not in the correct format. Check the file for correct json.');
268268
export const invalidNotebookFileErrorFormat = localize('DataScience.invalidNotebookFileError', '{0} is not a valid notebook file. Check the file for correct json.');
269269
export const nativeEditorTitle = localize('DataScience.nativeEditorTitle', 'Notebook Editor');

src/client/datascience/constants.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,12 +277,13 @@ export namespace Identifiers {
277277
export const SvgSizeTag = 'sizeTag={{0}, {1}}';
278278
export const InteractiveWindowIdentity = 'history://EC155B3B-DC18-49DC-9E99-9A948AA2F27B';
279279
export const InteractiveWindowIdentityScheme = 'history';
280+
export const DefaultCodeCellMarker = '# %%';
280281
}
281282

282283
export namespace CodeSnippits {
283284
export const ChangeDirectory = ['{0}', '{1}', 'import os', 'try:', '\tos.chdir(os.path.join(os.getcwd(), \'{2}\'))', '\tprint(os.getcwd())', 'except:', '\tpass', ''];
284285
export const ChangeDirectoryCommentIdentifier = '# ms-python.python added'; // Not translated so can compare.
285-
export const ImportIPython = '#%%\nfrom IPython import get_ipython\n\n';
286+
export const ImportIPython = '{0}\nfrom IPython import get_ipython\n\n{1}';
286287
export const MatplotLibInitSvg = `import matplotlib\n%matplotlib inline\n${Identifiers.MatplotLibDefaultParams} = dict(matplotlib.rcParams)\n%config InlineBackend.figure_formats = 'svg', 'png'`;
287288
export const MatplotLibInitPng = `import matplotlib\n%matplotlib inline\n${Identifiers.MatplotLibDefaultParams} = dict(matplotlib.rcParams)\n%config InlineBackend.figure_formats = 'png'`;
288289
}

src/client/datascience/editor-integration/codewatcher.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import { StopWatch } from '../../common/utils/stopWatch';
2222
import { captureTelemetry, sendTelemetryEvent } from '../../telemetry';
2323
import { ICodeExecutionHelper } from '../../terminals/types';
2424
import { CellMatcher } from '../cellMatcher';
25-
import { Commands, Telemetry } from '../constants';
25+
import { Commands, Identifiers, Telemetry } from '../constants';
2626
import { ICodeLensFactory, ICodeWatcher, IDataScienceErrorHandler, IInteractiveWindowProvider } from '../types';
2727

2828
@injectable()
@@ -268,9 +268,10 @@ export class CodeWatcher implements ICodeWatcher {
268268

269269
public async addEmptyCellToBottom(): Promise<void> {
270270
const editor = this.documentManager.activeTextEditor;
271+
const cellDelineator = this.defaultCellMarker;
271272
if (editor) {
272273
editor.edit((editBuilder) => {
273-
editBuilder.insert(new Position(editor.document.lineCount, 0), '\n\n#%%\n');
274+
editBuilder.insert(new Position(editor.document.lineCount, 0), `\n\n${cellDelineator}\n`);
274275
});
275276

276277
const newPosition = new Position(editor.document.lineCount + 3, 0); // +3 to account for the added spaces and to position after the new mark
@@ -286,6 +287,7 @@ export class CodeWatcher implements ICodeWatcher {
286287
const editor = this.documentManager.activeTextEditor;
287288
const cellMatcher = new CellMatcher();
288289
let index = 0;
290+
const cellDelineator = this.defaultCellMarker;
289291

290292
if (editor) {
291293
editor.edit((editBuilder) => {
@@ -295,14 +297,14 @@ export class CodeWatcher implements ICodeWatcher {
295297
if (cellMatcher.isCell(editor.document.lineAt(i).text)) {
296298
lastCell = false;
297299
index = i;
298-
editBuilder.insert(new Position(i, 0), '#%%\n\n');
300+
editBuilder.insert(new Position(i, 0), `${cellDelineator}\n\n`);
299301
break;
300302
}
301303
}
302304

303305
if (lastCell) {
304306
index = editor.document.lineCount;
305-
editBuilder.insert(new Position(editor.document.lineCount, 0), '\n#%%\n');
307+
editBuilder.insert(new Position(editor.document.lineCount, 0), `\n${cellDelineator}\n`);
306308
}
307309
});
308310
}
@@ -313,6 +315,10 @@ export class CodeWatcher implements ICodeWatcher {
313315
.then(() => this.advanceToRange(new Range(newPosition, newPosition)));
314316
}
315317

318+
private get defaultCellMarker(): string {
319+
return this.configService.getSettings().datascience.defaultCellMarker || Identifiers.DefaultCodeCellMarker;
320+
}
321+
316322
private onCodeLensFactoryUpdated(): void {
317323
// Update our code lenses.
318324
if (this.document) {
@@ -419,7 +425,7 @@ export class CodeWatcher implements ICodeWatcher {
419425

420426
if (editor) {
421427
editor.edit((editBuilder) => {
422-
editBuilder.insert(new Position(currentRange.end.line + 1, 0), '\n\n#%%\n');
428+
editBuilder.insert(new Position(currentRange.end.line + 1, 0), `\n\n${this.defaultCellMarker}\n`);
423429
});
424430
}
425431

src/client/datascience/gather/gather.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { Common } from '../../common/utils/localize';
1515
import { noop } from '../../common/utils/misc';
1616
import { CellMatcher } from '../cellMatcher';
1717
import { concatMultilineString } from '../common';
18+
import { Identifiers } from '../constants';
1819
import { CellState, ICell as IVscCell, IGatherExecution, INotebookExecutionLogger } from '../types';
1920

2021
/**
@@ -79,9 +80,13 @@ export class GatherExecution implements IGatherExecution, INotebookExecutionLogg
7980
if (cell === undefined) {
8081
return '';
8182
}
83+
84+
// Get the default cell marker as we need to replace #%% with it.
85+
const defaultCellMarker = this.configService.getSettings().datascience.defaultCellMarker || Identifiers.DefaultCodeCellMarker;
86+
8287
// Call internal slice method
8388
const slices = this._executionSlicer.sliceAllExecutions(cell);
84-
const program = slices[0].cellSlices.reduce(concat, '');
89+
const program = slices.length > 0 ? slices[0].cellSlices.reduce(concat, '').replace(/#%%/g, defaultCellMarker) : '';
8590

8691
// Add a comment at the top of the file explaining what gather does
8792
const descriptor = '# This file contains the minimal amount of code required to produce the code cell you gathered.\n';

0 commit comments

Comments
 (0)