-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlineOps.js
More file actions
138 lines (123 loc) · 5.58 KB
/
Copy pathlineOps.js
File metadata and controls
138 lines (123 loc) · 5.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*---------------------------------------------------------------------------------------------
* LevelCode — Notepad++ Pack
* Feature: Line operations (M1, feature 5) — the everyday Notepad++/TextFX set.
*
* Each line op works on the selected lines (selection expanded to whole lines), or the
* whole document if there's no selection — matching Notepad++ behavior. Case ops work
* per selection (or the word/line under the cursor when the selection is empty) and
* support multi-cursor.
*--------------------------------------------------------------------------------------------*/
// @ts-check
'use strict';
const vscode = require('vscode');
/** Whole-line range covering the active selection, or the whole document if empty. */
function lineRange(editor) {
const doc = editor.document;
const sel = editor.selection;
if (!sel.isEmpty) {
let endLine = sel.end.line;
// A selection that ends at column 0 of a line doesn't really include that line.
if (sel.end.character === 0 && endLine > sel.start.line) { endLine -= 1; }
return new vscode.Range(sel.start.line, 0, endLine, doc.lineAt(endLine).text.length);
}
const last = doc.lineCount - 1;
return new vscode.Range(0, 0, last, doc.lineAt(last).text.length);
}
function eol(doc) {
return doc.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n';
}
/** Run a lines-array transform over the target range as one edit. */
async function transformLines(editorArg, fn, opName) {
const editor = editorArg || vscode.window.activeTextEditor;
if (!editor) { vscode.window.showWarningMessage('LevelCode: open a text editor first.'); return; }
const doc = editor.document;
const range = lineRange(editor);
const lines = doc.getText(range).split(/\r?\n/);
const out = fn(lines);
if (out.join('\n') === lines.join('\n')) {
vscode.window.setStatusBarMessage(`LevelCode: ${opName} — no change`, 1500);
return;
}
await editor.edit((eb) => eb.replace(range, out.join(eol(doc))));
vscode.window.setStatusBarMessage(`$(check) LevelCode: ${opName} (${lines.length}→${out.length} lines)`, 2000);
}
// --- sorting ---------------------------------------------------------------
const collator = new Intl.Collator(undefined, { sensitivity: 'variant' });
const collatorCI = new Intl.Collator(undefined, { sensitivity: 'base' });
function numericKey(s) {
const m = String(s).trim().match(/^[+-]?\d+(\.\d+)?/);
return m ? parseFloat(m[0]) : NaN;
}
const sorters = {
asc: (a) => [...a].sort((x, y) => collator.compare(x, y)),
desc: (a) => [...a].sort((x, y) => collator.compare(y, x)),
ci: (a) => [...a].sort((x, y) => collatorCI.compare(x, y)),
numeric: (a) => [...a].sort((x, y) => {
const nx = numericKey(x), ny = numericKey(y);
if (isNaN(nx) && isNaN(ny)) { return collator.compare(x, y); }
if (isNaN(nx)) { return 1; }
if (isNaN(ny)) { return -1; }
return nx - ny;
})
};
// --- case conversion -------------------------------------------------------
function toTitle(s) {
return s.replace(/\w\S*/g, (w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase());
}
function toToggle(s) {
let r = '';
for (const ch of s) {
const lo = ch.toLowerCase(), up = ch.toUpperCase();
r += ch === lo && ch !== up ? up : (ch === up && ch !== lo ? lo : ch);
}
return r;
}
const casers = {
upper: (s) => s.toUpperCase(),
lower: (s) => s.toLowerCase(),
title: toTitle,
toggle: toToggle
};
async function convertCase(mode) {
const editor = vscode.window.activeTextEditor;
if (!editor) { vscode.window.showWarningMessage('LevelCode: open a text editor first.'); return; }
const fn = casers[mode];
await editor.edit((eb) => {
for (const sel of editor.selections) {
let range = sel;
if (sel.isEmpty) {
range = editor.document.getWordRangeAtPosition(sel.active) || editor.document.lineAt(sel.active.line).range;
}
eb.replace(range, fn(editor.document.getText(range)));
}
});
}
/** @param {vscode.ExtensionContext} context */
function registerLineOps(context) {
const reg = (id, fn) => context.subscriptions.push(vscode.commands.registerCommand(id, fn));
// Sorting
reg('levelcode.lines.sortAsc', () => transformLines(null, sorters.asc, 'sort ascending'));
reg('levelcode.lines.sortDesc', () => transformLines(null, sorters.desc, 'sort descending'));
reg('levelcode.lines.sortCaseInsensitive', () => transformLines(null, sorters.ci, 'sort (case-insensitive)'));
reg('levelcode.lines.sortNumeric', () => transformLines(null, sorters.numeric, 'sort numerically'));
// Dedup / blank lines / order
reg('levelcode.lines.removeDuplicates', () => transformLines(null, (a) => {
const seen = new Set(); const out = [];
for (const l of a) { if (!seen.has(l)) { seen.add(l); out.push(l); } }
return out;
}, 'remove duplicate lines'));
reg('levelcode.lines.removeDuplicatesAdjacent', () => transformLines(null, (a) =>
a.filter((l, i) => i === 0 || l !== a[i - 1]), 'remove consecutive duplicates'));
reg('levelcode.lines.removeEmpty', () => transformLines(null, (a) =>
a.filter((l) => l.trim().length > 0), 'remove empty lines'));
reg('levelcode.lines.reverse', () => transformLines(null, (a) => [...a].reverse(), 'reverse lines'));
// Aliases to robust built-ins (selection-aware already)
reg('levelcode.lines.join', () => vscode.commands.executeCommand('editor.action.joinLines'));
reg('levelcode.lines.trimTrailing', () => vscode.commands.executeCommand('editor.action.trimTrailingWhitespace'));
// Case
reg('levelcode.case.upper', () => convertCase('upper'));
reg('levelcode.case.lower', () => convertCase('lower'));
reg('levelcode.case.title', () => convertCase('title'));
reg('levelcode.case.toggle', () => convertCase('toggle'));
}
module.exports = { registerLineOps };