Last active
July 3, 2022 23:05
-
-
Save exceedsystem/0cb0d6973c15973ce37c99c006a11412 to your computer and use it in GitHub Desktop.
An example of 'Insert line numbers' macro for VSCodeMacros extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [VSCode Macros] extension | |
// https://marketplace.visualstudio.com/items?itemName=EXCEEDSYSTEM.vscode-macros | |
// License:MIT | |
const vscode = require('vscode'); | |
/** | |
* Macro configuration | |
*/ | |
module.exports.macroCommands = { | |
InsertLineNumbers: { | |
no: 1, | |
func: insertLineNumbers, | |
}, | |
}; | |
/** | |
* Insert line numbers | |
*/ | |
async function insertLineNumbers() { | |
const editor = vscode.window.activeTextEditor; | |
if (editor) { | |
const document = editor.document; | |
const selection = editor.selection; | |
const text = document.getText(selection); | |
if (text.length > 0) { | |
const firstLineNumberAsString = await vscode.window.showInputBox({ | |
value: 1, | |
prompt: 'Please enter the start line number.' | |
}); | |
if (firstLineNumberAsString === undefined) | |
return 'Cancelled.'; | |
let firstLineNumber = parseInt(firstLineNumberAsString); | |
if (isNaN(firstLineNumber)) | |
return 'Invalid line number.'; | |
editor.edit((editBuilder) => { | |
let resultText = ''; | |
let currentLineNumber = firstLineNumber; | |
// Add the line number to the first line. | |
resultText += formatLineNumber(currentLineNumber++); | |
for (let code of text) { | |
resultText += code; | |
if (code === '\n') { | |
// If code is LF then append the line number. | |
resultText += formatLineNumber(currentLineNumber++); | |
} | |
} | |
// Replace the selected text with line-numbered text. | |
editBuilder.replace(selection, resultText.toString()); | |
}); | |
} | |
} | |
// Convert the line number to your preferred format. | |
function formatLineNumber(lineNumber) { | |
return `${lineNumber}. `; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment