Created
March 7, 2018 03:07
-
-
Save Y-Less/20176cf5fb9d98e7a203ea4d1b06c9c6 to your computer and use it in GitHub Desktop.
Select two+ bits of code, hit the assigned hotkey, watch them swap positions.
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
# (c) Y_Less 2018 | |
# MPL 1.1 | |
# Multi-selection rotation script for Notepad++ Python Script plugin. | |
count = editor.getSelections() | |
if count > 1: | |
editor.beginUndoAction() | |
total = editor.getLength() | |
cuts = [] | |
initial = True | |
empty = True | |
# First, collate all the selections. | |
for i in xrange(count): | |
(a, b) = editor.getUserCharSelection() | |
c = editor.getCurrentPos() | |
# Get the start of the selection, or just the cursor. | |
empty = a == 0 and b == total | |
cuts.append({ | |
'idx': c if empty else a, | |
'initial': initial, | |
'empty': empty, | |
'start': a, | |
'cursor': c, | |
'length': 0 if empty else b - a, | |
'text': editor.getTextRange(a, b) | |
}) | |
initial = False | |
editor.rotateSelection() | |
# Remove the old versions. | |
cuts = sorted(cuts, key = lambda k: k['idx']) | |
offset = 0 | |
initial = 0 | |
for i in xrange(count): | |
if cuts[i]['initial']: | |
initial = i | |
cuts[i]['idx'] -= offset | |
cuts[i]['cursor'] -= offset | |
if not cuts[i]['empty']: | |
editor.deleteRange(cuts[i]['idx'], cuts[i]['length']) | |
offset += cuts[i]['length']; | |
# Insert the new versions. | |
offset = 0 | |
for i in xrange(count): | |
if not cuts[i]['empty']: | |
prev = -1 | |
# Find the best matching string to put here. | |
while cuts[i + prev]['empty']: | |
prev -= 1 | |
cuts[i]['idx'] += offset | |
editor.insertText(cuts[i]['idx'], cuts[i + prev]['text']) | |
offset += cuts[i + prev]['length'] | |
cuts[i]['newlen'] = cuts[i + prev]['length'] | |
# Restore the selections in the order they were found. | |
offset = False | |
empty = True | |
editor.clearSelections() | |
while not offset: | |
initial -= 1 | |
if empty: | |
if cuts[initial]['empty']: | |
editor.setSelection(cuts[initial]['idx'], cuts[initial]['idx']) | |
else: | |
editor.setSelection(cuts[initial]['idx'] + cuts[initial]['newlen'], cuts[initial]['idx']) | |
else: | |
if cuts[initial]['empty']: | |
editor.addSelection(cuts[initial]['idx'], cuts[initial]['idx']) | |
else: | |
editor.addSelection(cuts[initial]['idx'] + cuts[initial]['newlen'], cuts[initial]['idx']) | |
empty = False | |
offset = cuts[initial]['initial'] | |
editor.endUndoAction() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment