-
Notifications
You must be signed in to change notification settings - Fork 47
/
text_pastry.py
1948 lines (1869 loc) · 76.9 KB
/
text_pastry.py
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sublime
import sublime_plugin
import re
import operator
import datetime
import time
import uuid
import subprocess
import tempfile
import os
import json
import sys
import hashlib
import shlex
import unittest
import itertools
from os.path import expanduser, normpath, join, isfile
from decimal import *
SETTINGS_FILE = "TextPastry.sublime-settings"
def is_numeric(s):
if s is None:
return False
try:
int(s)
return True
except ValueError:
return False
def settings():
return sublime.load_settings(SETTINGS_FILE)
def global_settings(key, default=None):
return settings().get(key, default)
class TextPastryTools(object):
@staticmethod
def duplicate(view, edit, region, times):
for i in range(0, times):
# this code is from sublime text -> packages/default/duplicate.py
line = view.line(region)
line_contents = view.substr(line) + '\n'
view.insert(edit, line.begin(), line_contents)
view.sel().add(region)
class HistoryHandler(object):
_stack = None
index = 0
@classmethod
def setup(cls, items):
cls._stack = [''] + items
cls.index = 0
@classmethod
def append(cls, value):
# remove duplicate
cls.remove(value)
cls._stack.append(value)
cls.index = 0
@classmethod
def remove(cls, value):
if value in cls._stack:
index = cls._stack.index(value)
del cls._stack[index]
@classmethod
def set(cls, value, index=None):
cls._stack[cls.normalize_index(index)] = value
@classmethod
def normalize_index(cls, index):
original = index
index = cls.index if index is None else index
if index:
last = len(cls._stack) - 1 if len(cls._stack) > 0 else 0
# check if index is in bounds
if index < 0: index = last
if index > last: index = 0
return index
@classmethod
def next(cls):
cls.index = cls.normalize_index(cls.index + 1)
@classmethod
def prev(cls):
cls.index = cls.normalize_index(cls.index - 1)
@classmethod
def get(cls, index=None):
return cls._stack[cls.normalize_index(index)]
@classmethod
def empty(cls):
return cls._stack is None or len(cls._stack) == 0
@classmethod
def size(cls):
return len(cls._stack)
@classmethod
def current_index(cls):
return cls.index
class HistoryManager(object):
file = None
def __init__(self, remove_duplicates=True):
self.settings = sublime.load_settings(self.file)
self.remove_duplicates = remove_duplicates
def generate_key(self, data):
return hashlib.md5(json.dumps(data).encode('UTF-8')).hexdigest()
def history(self):
history = self.settings.get("history", [])
if isinstance(history, dict):
history = []
return history
def items(self):
entries = [item['data'] for item in self.history() if 'data' in item]
return entries[-self.max():]
def max(self):
return self.settings.get("history_max_entries", 100)
def save(self, history):
if history is not None:
self.settings.set("history", history)
sublime.save_settings(self.file)
def append(self, data, label=None):
if not data:
return
history = self.history()
key = self.generate_key(data)
# convert
if isinstance(history, dict):
history = []
history[:] = [item for item in history if 'key' in item and not item['key'] == key]
history.append({'key': key, 'data': data, 'label': label})
# set as last command
self.settings.set('last_command', data)
self.save(history)
def remove(self, key):
history = self.history()
history[:] = [item for item in history if item['key'] == key]
def clear(self):
self.save([])
class TextPastryHistoryNavigatorCommand(sublime_plugin.TextCommand):
def __init__(self, *args, **kwargs):
super(TextPastryHistoryNavigatorCommand, self).__init__(*args, **kwargs)
self.current = None
def run(self, edit, reverse=False):
HH = HistoryHandler
if HH.index == 0:
current = self.view.substr(sublime.Region(0, self.view.size()))
HH.set(current)
if reverse: HH.prev()
else: HH.next()
self.view.erase(edit, sublime.Region(0, self.view.size()))
self.view.insert(edit, 0, HH.get())
if HH.current_index():
sublime.status_message("History item: " + str(HH.current_index()) + " of " + str(HH.size() - 1))
else:
sublime.status_message("Current")
def is_enabled(self, *args, **kwargs):
return not HistoryHandler.empty()
class CommandLineHistoryManager(HistoryManager):
file = "TextPastryHistory.sublime-settings"
field = 'text'
def generate_key(self, data):
return hashlib.md5(data[self.field].encode('UTF-8')).hexdigest()
def items(self):
entries = [item['data'][self.field] for item in self.history() if 'data' in item and self.field in item['data']]
return entries[-self.max():]
def append(self, data, label=None):
if self.field in data and len(data[self.field]) > 0:
super(CommandLineHistoryManager, self).append(data, label)
HistoryHandler.append(data[self.field])
class OverlayHistoryManager(HistoryManager):
file = "TextPastryHistory.sublime-settings"
field = 'text'
def generate_key(self, data):
return hashlib.md5(data[self.field].encode('UTF-8')).hexdigest()
def items(self):
entries = self.history()[-self.max():]
entries.reverse()
return entries
def append(self, data, label=None):
if self.field in data and len(data[self.field]) > 0:
super(CommandLineHistoryManager, self).append(data, label)
HistoryHandler.append(data[self.field])
class Command(object):
def __init__(self, options=None, view=None, edit=None, env=None, *args, **kwargs):
self.counter = 0
self.options = options
self.stack = []
self.view = view
self.edit = edit
self.env = env
def init(self, view, items=None):
if items: self.stack = items
def previous(self):
return self.stack[self.counter - 1]
def current(self):
return text[self.counter]
def next(self, value, index, region):
val = self.stack[self.counter]
self.counter += 1
return val
def has_next(self):
return (self.counter) < len(self.stack)
@staticmethod
def create(cmd, items=None, options=None):
return getattr(sys.modules[__name__], cmd)(items)
class InfiniteCommand(Command):
def has_next(self):
return True
class BackreferenceCommand(Command):
def init(self, view, items=None):
selections = []
if view.sel():
for region in view.sel():
selections.append(view.substr(region))
values = []
for idx, index in enumerate(map(int, items)):
if idx >= len(selections): break
i = index - 1
if i >= 0 and i < len(selections):
values.append(selections[i])
else:
values.append(None)
# fill up
for idx, value in enumerate(selections):
if len(values) + 1 < idx:
values.append(value)
self.stack = values
class UuidCommand(InfiniteCommand):
def next(self, value, index, region):
text = str(uuid.uuid4())
if self.is_upper_case():
text = text.upper()
self.stack.append(text)
return text
def is_upper_case(self):
upper_case = False
if self.options:
upper_case = self.options.get("uppercase", False)
return upper_case
class ShellCommand(InfiniteCommand):
cmd = '/bin/sh'
shell = False
def __init__(self, *args, **kwargs):
super(ShellCommand, self).__init__(*args, **kwargs)
if sublime.platform() == 'windows':
cmd = 'cmd.exe'
shell = True
def settings(self):
return global_settings(self.cmd, {})
def command(self, script):
return shlex.split(script)
def work_dir(self):
folder = self.options.get("folder", None)
return folder if folder else expanduser("~")
def proc(self, env, script):
command, cwd = self.command(script), self.work_dir()
if command and cwd and script:
sp = subprocess
return sp.Popen(command, env=env, cwd=cwd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.STDOUT)
def execute(self, script):
env = os.environ.copy()
for path in global_settings('path', {}).get(sublime.platform(), []):
env["PATH"] += os.pathsep + path
proc = self.proc(env, script)
if proc:
print('Running script:', script)
result = proc.communicate()[0]
if proc.returncode == 0:
print('script result:', result.decode('UTF-8'))
return result.decode('UTF-8')
else:
s = 'error while processing script with {CMD}: {RESULT}'
sublime.error_message(s.format(
CMD=self.cmd,
RESULT=result.decode('UTF-8')
))
def get_fcontent(self, file):
path = normpath(join(self.cwd(), file))
if isfile(path):
with open(path, "r") as f:
script = f.read()
return script
def script(self):
script = self.options.get("script", None)
file = self.options.get("file", None)
if file:
script = self.get_fcontent(file)
elif self.check_wrap(script):
script = self.wrap(script)
return script
def check_wrap(self, script):
return self.options.get("wrap", True)
def wrap(self, script):
return script
def next(self, value, index, region):
self.value = value
self.index = index
self.begin = region.begin()
self.end = region.end()
return self.execute(self.script())
class NodejsCommand(ShellCommand):
cmd = 'node'
def command(self, script):
return [cmd, '-e', script]
def wrap(self, script):
# some sugar
if not 'return ' in script and not ';' in script:
script = "value = " + script
# generate context information
meta = dict(
value=json.dumps(self.value),
index=self.index,
begin=self.begin,
end=self.end,
length=value.length,
row=0,
column=0,
selection_type=0
)
script = """
var result = (function(value, index, begin, end) {
{SCRIPT};
return value;
}({VALUE}, {INDEX}, {BEGIN}, {END}));
process.stdout.write("" + result);
""".format(
SCRIPT=script,
VALUE=json.dumps(self.value),
INDEX=self.index,
BEGIN=self.begin,
END=self.end
)
return script
class PythonCommand(ShellCommand):
cmd = 'python'
def command(self, script):
print('executing python', script)
return [self.cmd, '-B', '-c', script]
def wrap(self, script):
# define global imports here
code = ['import sys']
# extend syspath with config
sys_paths = self.settings().get('sys.path.append', [])
code.extend(['sys.path.append("' + p + '")' for p in sys_paths])
# custom imports
code.extend(self.imports())
# generate wrapper code
code.extend([
'def tpscript(value, index, begin, end):',
' return ' + script,
"sys.stdout.write(tpscript('{VALUE}', {INDEX}, {BEGIN}, {END}))".format(
SCRIPT=script.replace("'", r"\'"),
VALUE=re.escape(self.value),
INDEX=self.index,
BEGIN=self.begin,
END=self.end
)
])
return '\n'.join(code)
def imports(self):
imports = []
for i in self.settings().get('import', []):
if isinstance(i, dict) and len(i) == 1:
for d in iter(i):
print(i)
if len(i[d]):
imports.append('from ' + d + ' import ' + ','.join(i[d]))
else:
imports.append('import ' + d)
else:
imports.append('import ' + i)
return imports
class RubyCommand(ShellCommand):
cmd = 'ruby'
def command(self, script):
return [cmd, '-e', script]
def wrap(self, script):
wrapper = """
def tpscript(value, index, begin, end)
{SCRIPT}
end
tpscript('{VALUE}', {INDEX}, {BEGIN}, {END})
""".format(
SCRIPT=script,
VALUE=json.dumps(self.value),
INDEX=self.index,
BEGIN=self.begin,
END=self.end
)
return script
class TextPastryShowCommandLine(sublime_plugin.WindowCommand):
def run(self, text, execute=False):
if not self.window.active_view():
return
if execute:
self.on_done(text, False)
return
if not hasattr(self, 'history'):
self.history = CommandLineHistoryManager()
HistoryHandler.setup(self.history.items())
self.show_input_panel('Text Pastry Command:', text)
def on_done(self, text, history=True):
parser = Parser()
result = parser.parse(text)
if result and 'command' in result:
result['text'] = text
if history:
self.history.append(data=result, label=text)
command = result['command']
args = result['args'] if 'args' in result else None
if 'context' in result and result['context'] == 'view':
self.window.active_view().run_command(command, args)
else:
self.window.run_command(command, args)
def show_input_panel(self, label, text):
HistoryHandler.index = 0
view = self.window.show_input_panel(label, text, self.on_done, None, None)
settings = view.settings()
settings.set('is_widget', False)
settings.set('gutter', False)
settings.set('rulers', [])
settings.set('spell_check', False)
settings.set('word_wrap', False)
settings.set('draw_minimap_border', False)
settings.set('draw_indent_guides', False)
settings.set('highlight_line', False)
settings.set('line_padding_top', 0)
settings.set('line_padding_bottom', 0)
settings.set('auto_complete', False)
settings.set('text_pastry_command_line', True)
class TextPastryInsertTextCommand(sublime_plugin.TextCommand):
def run(self, edit, text=None, separator=None, clipboard=False,
items=None, regex=False, keep_selection=None, update_selection=None,
repeat=None, strip=None, threshold=1, align=None, by_rows=False, repeat_word=0):
if separator: separator = separator.encode('utf8').decode("unicode-escape")
if clipboard: text = sublime.get_clipboard()
if text:
if regex: items = re.split(separator, text)
else: items = text.split(separator)
# could make a threshold setting...
if items and len(items) >= threshold:
regions = []
sel = self.view.sel()
if repeat_word > 1:
items = list(itertools.chain.from_iterable(itertools.repeat(item, repeat_word) for item in items))
if by_rows == True:
items = self.by_rows(items, sel)
if strip is None:
strip = False
if separator == '\\n' and settings().has("clipboard_strip_newline"): strip = settings().get("clipboard_strip_newline")
# initialize repeat
if repeat is None:
if clipboard and settings().has("repeat_clipboard"):
repeat = settings().get("repeat_clipboard")
elif settings().has("repeat_words"):
repeat = settings().get("repeat_words")
if repeat:
while (len(items) < len(sel)):
items.extend(items)
last_region = None
for idx, region in enumerate(sel):
if idx < len(items):
current = items[idx]
if strip:
current = current.strip()
if align == 'prepend':
self.view.insert(edit, region.begin(), current)
elif align == 'append':
self.view.insert(edit, region.end(), current)
else:
self.view.replace(edit, region, current)
else:
regions.append(region)
last_region = region
if keep_selection is None:
keep_selection = settings().get("keep_selection", False)
if update_selection is None:
update_selection = settings().get("update_selection", None)
# clone the selection
cursorPos = [(r.begin(), r.end()) for r in sel];
if not keep_selection:
sel.clear()
# add untouched regions
for region in regions:
sel.add(sublime.Region(region.begin(), region.end()))
# add cursor if there is none in the current view
if len(sel) == 0:
(begin, end) = cursorPos[-1]
sel.add(sublime.Region(begin, end))
else:
if update_selection == "begin":
sel.clear()
for begin, end in cursorPos:
sel.add(sublime.Region(begin, begin))
elif update_selection == "end":
sel.clear()
for begin, end in cursorPos:
sel.add(sublime.Region(end, end))
else:
sublime.status_message("No text found for Insert Text, fall back to auto_step")
self.view.run_command("text_pastry_auto_step", {"text": text})
def by_rows(self, data, sel):
rows = self.create_matrix(sel)
return self.prep_data(data, rows)
def create_matrix(self, sel):
rows = []
r = None
c = None
for region in sel:
row, col = self.view.rowcol(region.begin())
if (r == None):
r = row
c = [1]
elif (r != row):
rows.append(c)
# new row
r = row
c = [1]
else:
c.append(1)
rows.append(c)
# extend colums of rows
mc = self.count_cols(rows)
for r in rows:
i = mc - len(r)
if (i > 0):
r.extend([0]*i)
return rows
def count_cols(self, rows):
# fill rows
max_cols = 0
for r in rows:
cols = 0
for c in r:
cols += 1
if cols > max_cols:
max_cols = cols
return max_cols
def prep_data(self, data, rows):
prepped_data = []
t1 = [list(i) for i in zip(*rows)];
index = 0
for row in t1:
for idx, val in enumerate(row):
if val == 1 and len(data) > index:
row[idx] = data[index]
index += 1
else:
row[idx] = None
t2 = [list(i) for i in zip(*t1)]
for row in t2:
prepped_data.extend([i for i in row if i != None])
return prepped_data
class TextPastryWordsCommand(sublime_plugin.TextCommand):
def run(self, edit, text, repeat=None):
result = WordsParser(text).parse()
if result and 'command' in result and 'args' in result:
if repeat is not None:
result['args']['repeat'] = repeat
self.view.run_command(result['command'], result['args'])
class TextPastryShowMenu(sublime_plugin.WindowCommand):
def create_main(self):
self.overlay = Overlay()
history = self.history_manager.items()
[self.overlay.addHistoryItem(item) for item in history[:2]]
if len(history) > 0:
self.overlay.addSpacer()
x = selection_count = len(self.window.active_view().sel())
self.overlay.addMenuItem("\\i", "From 1 to {0}".format(x))
self.overlay.addMenuItem("\\i0", "From 0 to " + str(x - 1))
self.overlay.addMenuItem("\\i(N,M)", "From N to X by M")
self.overlay.addSpacer()
if sublime.get_clipboard():
self.overlay.addMenuItem("\\p(\\n)", "Paste Lines")
self.overlay.addMenuItem("\\p", "Paste")
self.overlay.addSpacer()
self.overlay.addMenuItem("words", "Enter a list of words")
uuid_label = 'UUID' if global_settings("force_uppercase_uuid", False) else 'uuid'
self.overlay.addMenuItem(uuid_label, "Generate UUIDs")
self.overlay.addSpacer()
if len(history) > 0: self.overlay.addMenuItem("history", "Show history")
self.overlay.addMenuItem("settings", "Show settings")
def create_history(self):
self.overlay = Overlay()
history = self.history_manager.items()
[self.overlay.addHistoryItem(item) for item in history]
self.overlay.addSpacer()
self.overlay.addMenuItem("clear_hist", "Clear history")
self.overlay.addMenuItem("back", "Back to menu")
def create_settings(self):
self.overlay = Overlay()
repeat_words = global_settings("repeat_words", False)
repeat_clipboard = global_settings("repeat_clipboard", False)
clipboard_strip_newline = global_settings("clipboard_strip_newline", False)
keep_selection = global_settings("keep_selection", False)
force_uppercase_uuid = global_settings("force_uppercase_uuid", False)
self.overlay.addSetting("repeat_words", repeat_words)
self.overlay.addSetting("repeat_clipboard", repeat_clipboard)
self.overlay.addSetting("clipboard_strip_newline", clipboard_strip_newline)
self.overlay.addSetting("keep_selection", keep_selection)
self.overlay.addSetting("force_uppercase_uuid", force_uppercase_uuid)
self.overlay.addSpacer()
self.overlay.addMenuItem(command="default", args={"file": sublime.packages_path() + "/Text Pastry/TextPastry.sublime-settings"}, label="Open default settings")
self.overlay.addMenuItem(command="user", args={"file": sublime.packages_path() + "/User/TextPastry.sublime-settings"}, label="Open user settings")
if self.back:
self.overlay.addSpacer()
self.overlay.addMenuItem("back", "Back to menu")
def run(self, history=False, settings=False, back=True):
if not self.window.active_view():
return
if not hasattr(self, 'history_manager'):
self.history_manager = OverlayHistoryManager()
self.back = back
try:
selection_count = len(self.window.active_view().sel())
if history:
self.create_history()
elif settings:
self.create_settings()
else:
self.create_main()
if self.overlay and self.overlay.is_valid():
self.show_quick_panel(self.overlay.items(), self.on_done, sublime.MONOSPACE_FONT)
except ValueError:
sublime.status_message("Error while showing Text Pastry overlay")
def on_done(self, index):
self.window.run_command("hide_overlay")
item = self.overlay.get(index)
if item and item.command:
if item.type == HistoryItem.type:
sublime.status_message("redo history")
command = item.command
text = item.text
separator = item.separator
# insert nums for history compatibility
if command == "insert_nums":
sublime.status_message("text_pastry_range: " + text)
(start, step, padding) = map(str, text.split(" "))
self.window.run_command("text_pastry_range", {"start": start, "step": step, "padding": padding})
elif command == "text_pastry_insert_text":
self.window.run_command(command, {"text": text, "separator": separator})
else:
self.window.run_command(item.command, item.args)
elif item.command == "history":
self.window.run_command("text_pastry_show_menu", {"history": True})
return
elif item.command == "settings":
self.window.run_command("text_pastry_show_menu", {"settings": True})
return
elif item.command == "clear_hist":
self.history_manager.clear()
elif item.command == "back":
self.window.run_command("text_pastry_show_menu")
elif item.command == "cancel" or item.command == "close":
pass
elif item.command == "\\p":
cb = sublime.get_clipboard()
if cb:
self.history_manager.append(data={"command": "text_pastry_insert_text", "args": {"clipboard": True}}, label=item.label)
self.window.run_command("text_pastry_insert_text", {"text": cb, "clipboard": True})
else:
sublime.message_dialog("No Clipboard Data available")
elif item.command == "\\p(\\n)":
cb = sublime.get_clipboard()
if cb:
self.history_manager.append(data={"command": "text_pastry_insert_text", "args": {"text": cb, "separator": "\\n", "clipboard": True}}, label=item.label)
self.window.run_command("text_pastry_insert_text", {"text": cb, "separator": "\\n", "clipboard": True})
else:
sublime.message_dialog("No Clipboard Data available")
elif item.command == "\\i":
self.history_manager.append(data={"command": "text_pastry_range", "args": {"start": 1, "step": 1, "padding": 1}}, label=item.label)
self.window.run_command("text_pastry_range", {"start": 1, "step": 1, "padding": 1})
elif item.command == "\\i0":
self.history_manager.append(data={"command": "text_pastry_range", "args": {"start": 0, "step": 1, "padding": 1}}, label=item.label)
self.window.run_command("text_pastry_range", {"start": 0, "step": 1, "padding": 1})
elif item.command.lower() == "uuid":
self.history_manager.append(data={"command": "text_pastry_uuid", "args": {"uppercase": False}}, label=item.label)
self.window.run_command("text_pastry_uuid", {"uppercase": False})
elif item.command == "words":
self.window.run_command("text_pastry_show_command_line", {"text": item.command + " "})
elif item.command == "text_pastry_setting":
item.args['value'] = not item.args.get('value', False)
self.window.run_command("text_pastry_setting", item.args)
self.window.run_command("text_pastry_show_menu", {"settings": True, "back": self.back})
elif item.command == "user" or item.command == "default":
self.window.run_command("open_file", item.args)
elif item.command == "\\i(N,M)":
self.window.run_command("text_pastry_show_command_line", {"text": item.command})
elif len(item.command):
self.window.run_command(item.command, item.args)
else:
sublime.status_message("Unknown command: " + item.command)
else:
sublime.status_message("No item selected")
def show_quick_panel(self, items, on_done, flags):
# Sublime 3 does not allow calling show_quick_panel from on_done, so we need to set a timeout here.
sublime.set_timeout(lambda: self.window.show_quick_panel(items, on_done, flags), 10)
class TextPastryPasteCommand(sublime_plugin.TextCommand):
def run(self, edit):
try:
text = sublime.get_clipboard()
if text is not None and len(text) > 0:
regions = []
sel = self.view.sel()
items = text.split("\n")
if len(items) == 1: items = [text]
strip = True
for idx, region in enumerate(sel):
if idx < len(items):
row = items[idx].strip()
if region.empty():
sublime.status_message("empty")
row = self.view.substr(self.view.line(self.view.line(region).begin() - 1)) + "\n"
i = 0
if len(row.strip()): i = self.view.insert(edit, region.end(), row)
regions.append(sublime.Region(region.end() + i, region.end() + i))
else:
sublime.status_message("selection")
self.view.replace(edit, region, row)
i = len(row)
regions.append(sublime.Region(region.begin() + i, region.begin() + i))
sel.clear()
for region in regions:
sel.add(region)
pass
else:
sublime.status_message("No text found for Insert Text, canceled")
except ValueError:
sublime.status_message("Error while executing Insert Text, canceled")
pass
class TextPastryRangeParserCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
result = RangeCommandParser(text).parse()
self.view.run_command(result['command'], result['args'])
class TextPastryRangeCommand(sublime_plugin.TextCommand):
def run(self, edit, start=None, stop=None, step=1, padding=1, fillchar='0', justify=None,
align=None, prefix=None, suffix=None, repeat_increment=None, loop=None, **kwargs):
print('found range command', start, stop, step)
start = int(start) if is_numeric(start) else None
stop = int(stop) if is_numeric(stop) else None
step = int(step) if is_numeric(step) else 1
padding = int(padding) if is_numeric(padding) else 0
# duplicate lines and add to selection on repeat
if stop is not None:
if start is None:
if stop == 1:
start = len(self.view.sel())
elif stop == 0:
start = len(self.view.sel()) - 1
multiplier = 1
if is_numeric(repeat_increment):
multiplier *= int(repeat_increment)
if is_numeric(loop):
multiplier *= int(loop)
repeat = len(range(start, stop, step))
if multiplier > 1:
repeat = (repeat + 1) * multiplier - 1
sel = self.view.sel()
if len(sel) == 1:
TextPastryTools.duplicate(self.view, edit, sel[0], repeat)
if start is None:
start = 0
# adjust stop if none was given
if stop is None:
stop = start + (len(self.view.sel()) + 1) * step
if global_settings('range_include_end_index', True):
stop += step
# if stop is negative, step needs to be negative aswell
if (start > stop and step > 0):
step = step * -1
items = [str(x) for x in range(start, stop, step)]
if repeat_increment and repeat_increment > 0:
tmp = items
items = []
for val in tmp:
for x in range(repeat_increment):
items.append(val)
if padding > 1:
fillchar = fillchar if fillchar is not None else '0'
just = str.ljust if justify == 'left' else str.rjust
items = [self.pad(x, just, padding, fillchar) for x in items]
# apply prefix/suffix
if prefix:
items = [prefix + x for x in items]
if suffix:
items = [x + suffix for x in items]
self.view.run_command("text_pastry_insert_text", {"items": items, "align": align})
def pad(self, s, just, padding, fillchar):
if s.startswith('-'):
return '-' + just(s[1:], padding, fillchar)
else:
return just(s, padding, fillchar)
class TextPastryBinCommand(sublime_plugin.TextCommand):
def run(self, edit, start=None, stop=None, step=1, padding=1, fillchar='0', justify=None,
align=None, prefix=None, suffix=None, repeat_increment=None, loop=None, **kwargs):
print('found bin command', start, stop, step)
start = int(start) if is_numeric(start) else None
stop = int(stop) if is_numeric(stop) else None
step = int(step) if is_numeric(step) else 1
padding = int(padding) if is_numeric(padding) else 0
# duplicate lines and add to selection on repeat
if stop is not None:
if start is None:
if stop == 1:
start = len(self.view.sel())
elif stop == 0:
start = len(self.view.sel()) - 1
multiplier = 1
if is_numeric(repeat_increment):
multiplier *= int(repeat_increment)
if is_numeric(loop):
multiplier *= int(loop)
repeat = len(range(start, stop, step))
if multiplier > 1:
repeat = (repeat + 1) * multiplier - 1
sel = self.view.sel()
if len(sel) == 1:
TextPastryTools.duplicate(self.view, edit, sel[0], repeat)
if start is None:
start = 0
# adjust stop if none was given
if stop is None:
stop = start + (len(self.view.sel()) + 1) * step
if global_settings('range_include_end_index', True):
stop += step
# if stop is negative, step needs to be negative aswell
if (start > stop and step > 0):
step = step * -1
items = [str(bin(x)).split("b")[1] for x in range(start, stop, step)]
if repeat_increment and repeat_increment > 0:
tmp = items
items = []
for val in tmp:
for x in range(repeat_increment):
items.append(val)
if padding > 1:
fillchar = fillchar if fillchar is not None else '0'
just = str.ljust if justify == 'left' else str.rjust
items = [self.pad(x, just, padding, fillchar) for x in items]
# apply prefix/suffix
if prefix:
items = [prefix + x for x in items]
if suffix:
items = [x + suffix for x in items]
self.view.run_command("text_pastry_insert_text", {"items": items, "align": align})
def pad(self, s, just, padding, fillchar):
if s.startswith('-'):
return '-' + just(s[1:], padding, fillchar)
else:
return just(s, padding, fillchar)
class TextPastryDecimalRangeCommand(sublime_plugin.TextCommand):
def run(self, edit, start=None, stop=None, step=1, padding=1, fillchar='0', justify=None,
align=None, prefix=None, suffix=None, repeat_increment=None, loop=None, precision=0,
**kwargs):
print('found range command', start, stop, step, padding, precision, justify)
start = Decimal(start) if self.is_decimal(start) else None
stop = Decimal(stop) if self.is_decimal(stop) else None
step = Decimal(step) if self.is_decimal(step) else 1
padding = int(padding) if is_numeric(padding) else 0
precision = int(precision) if is_numeric(precision) else 0
# duplicate lines and add to selection on repeat
if stop is not None:
if start is None:
if stop == 1:
start = Decimal(len(self.view.sel()))
elif stop == 0:
start = Decimal(len(self.view.sel()) - 1)
multiplier = 1
if is_numeric(repeat_increment):
multiplier *= repeat_increment
if is_numeric(loop):
multiplier *= loop
repeat = len(list(self.drange(start, stop, step)))
if multiplier > 1:
repeat = (repeat + 1) * multiplier - 1
sel = self.view.sel()
if len(sel) == 1:
TextPastryTools.duplicate(self.view, edit, sel[0], repeat)
if start is None:
start = Decimal(0)
# adjust stop if none was given
if stop is None:
stop = start + Decimal(len(self.view.sel()) + 1) * step
if global_settings('range_include_end_index', True):
stop += step
items = [x for x in self.drange(start, stop, step)]
if repeat_increment and repeat_increment > 0:
tmp = items
items = []
for val in tmp:
for x in range(repeat_increment):
items.append(val)
print('range command args', start, stop, step, "items", items)
if precision > 1:
items = ["{:.{}f}".format(x, precision) for x in items]
if not justify:
justify = 'right'
if padding > 1:
fillchar = fillchar if fillchar is not None else '0'
just = str.ljust if justify == 'left' else str.rjust
items = [self.pad(str(x), just, padding, fillchar) for x in items]
# apply prefix/suffix
if prefix:
items = [prefix + x for x in items]
if suffix:
items = [x + suffix for x in items]
# make sure we deliver strings
items = [str(x) for x in items]
self.view.run_command("text_pastry_insert_text", {"items": items, "align": align})
def pad(self, s, just, padding, fillchar):
if s.startswith('-'):
return '-' + just(s[1:], padding, fillchar)
else:
return just(s, padding, fillchar)
def drange(self, start, stop, step):
r = start
if start <= stop:
while r <= stop:
yield r
r += getcontext().abs(step)
if start > stop:
while r >= stop:
yield r
r -= getcontext().abs(step)
def is_decimal(self, s):
if s is None:
return False
try:
Decimal(s)
return True
except ValueError:
return False
class TextPastryDecimalGeometricSequenceCommand(sublime_plugin.TextCommand):
def run(self, edit, start=None, stop=None, faktor=2, padding=1, fillchar='0', justify=None,
align=None, prefix=None, suffix=None, repeat_increment=None, loop=None, precision=0,
**kwargs):
print('found faktor command', start, stop, faktor, padding, precision, justify)
start = Decimal(start) if self.is_decimal(start) else None
stop = Decimal(stop) if self.is_decimal(stop) else None
faktor = Decimal(faktor) if self.is_decimal(faktor) else 1
padding = int(padding) if is_numeric(padding) else 0
precision = int(precision) if is_numeric(precision) else 0
# duplicate lines and add to selection on repeat
if stop is not None:
if start is None:
if stop == 1:
start = Decimal(len(self.view.sel()))
elif stop == 0:
start = Decimal(len(self.view.sel()) - 1)
multiplier = 1
if is_numeric(repeat_increment):
multiplier *= repeat_increment
if is_numeric(loop):
multiplier *= loop
repeat = len(list(self.gsequence(start, stop, faktor)))
if multiplier > 1:
repeat = (repeat + 1) * multiplier - 1
sel = self.view.sel()
if len(sel) == 1:
TextPastryTools.duplicate(self.view, edit, sel[0], repeat)
if start is None:
start = Decimal(1)
# adjust stop if none was given
if stop is None:
stop = start + Decimal(len(self.view.sel()) + 1) * faktor
if global_settings('range_include_end_index', True):
stop *= faktor