Skip to content

Instantly share code, notes, and snippets.

@exceedsystem
Created December 21, 2020 12:17
Show Gist options
  • Save exceedsystem/755d311e8141c322bce3b96d8240c4fb to your computer and use it in GitHub Desktop.
Save exceedsystem/755d311e8141c322bce3b96d8240c4fb to your computer and use it in GitHub Desktop.
An example of 'Remove Duplicate Lines' macro for VSCodeMacros extension
// [VSCode Macros] extension
// https://marketplace.visualstudio.com/items?itemName=EXCEEDSYSTEM.vscode-macros
const vscode = require('vscode');
/**
* Macro configuration
*/
module.exports.macroCommands = {
RemoveDuplicateLines: {
no: 1,
func: removeDupLines
},
};
/**
* Remove duplicate lines macro function
*/
function removeDupLines() {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return 'Editor is not opening.';
}
// get the selected text
const document = editor.document;
const selection = editor.selection;
const text = document.getText(selection);
if (text.length > 0) {
// get a document EOL characters
const documentEOL = {
1: '\n',
2: '\r\n'
} [document.eol];
// split text by newline
const selectedLines = text.split(documentEOL);
// mark the duplicates
const appeared = new Set();
const uniqueLines = selectedLines.map((lineText, rowIndex) => {
if (lineText.length > 0 && appeared.has(lineText)) {
return {
text: lineText,
row: -1
};
}
appeared.add(lineText);
return {
text: lineText,
row: rowIndex
};
});
editor.edit(editBuilder => {
// replace selected text without duplicate lines
const replaced = uniqueLines
.filter((value) => value.row > -1)
.map((value) => value.text)
.join(documentEOL);
editBuilder.replace(selection, replaced);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment