forked from JamesShaker/SublimeHOL
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sublimehol.py
863 lines (700 loc) · 28.4 KB
/
sublimehol.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
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Wojciech Bederski (wuub.net)
# All rights reserved.
# See LICENSE.txt for details.
from __future__ import absolute_import, unicode_literals, print_function, division
import re
import os
import sys
import os.path
import threading
import traceback
from datetime import datetime
import sublime
import sublime_plugin
try:
from . import ansi
import queue
from . import sublimehol_build_system_hack
from . import repls
from .repllibs import PyDbLite
unicode_type = str
PY2 = False
except ImportError:
import ansi
import sublimehol_build_system_hack
import repls
from repllibs import PyDbLite
import Queue as queue
unicode_type = unicode
PY2 = True
PLATFORM = sublime.platform().lower()
SETTINGS_FILE = 'HOL.sublime-settings'
SUBLIME2 = sublime.version() < '3000'
RESTART_MSG = """
#############
## RESTART ##
#############
"""
class HolReplInsertTextCommand(sublime_plugin.TextCommand):
def run(self, edit, pos, text):
self.view.set_read_only(False) # make sure view is writable
self.view.insert(edit, int(pos), text)
class HolReplEraseTextCommand(sublime_plugin.TextCommand):
def run(self, edit, start, end):
self.view.set_read_only(False) # make sure view is writable
self.view.erase(edit, sublime.Region(int(start), int(end)))
class HolReplPass(sublime_plugin.TextCommand):
def run(self, edit):
pass
class ReplReader(threading.Thread):
def __init__(self, repl):
super(ReplReader, self).__init__()
self.repl = repl
self.daemon = True
self.queue = queue.Queue()
def run(self):
r = self.repl
q = self.queue
while True:
result = r.read()
q.put(result)
if result is None:
break
class HistoryMatchList(object):
def __init__(self, command_prefix, commands):
self._command_prefix = command_prefix
self._commands = commands
self._cur = len(commands) # no '-1' on purpose
def current_command(self):
if not self._commands:
return ""
return self._commands[self._cur]
def prev_command(self):
self._cur = max(0, self._cur - 1)
return self.current_command()
def next_command(self):
self._cur = min(len(self._commands) - 1, self._cur + 1)
return self.current_command()
class History(object):
def __init__(self):
self._last = None
def push(self, command):
cmd = command.rstrip()
if not cmd or cmd == self._last:
return
self.append(cmd)
self._last = cmd
def append(self, cmd):
raise NotImplementedError()
def match(self, command_prefix):
raise NotImplementedError()
class MemHistory(History):
def __init__(self):
super(MemHistory, self).__init__()
self._stack = []
def append(self, cmd):
self._stack.append(cmd)
def match(self, command_prefix):
matching_commands = []
for cmd in self._stack:
if cmd.startswith(command_prefix):
matching_commands.append(cmd)
return HistoryMatchList(command_prefix, matching_commands)
class PersistentHistory(MemHistory):
def __init__(self, external_id):
super(PersistentHistory, self).__init__()
path = os.path.join(sublime.packages_path(), "User", ".HOLHistory")
if not os.path.isdir(path):
os.makedirs(path)
filepath = os.path.join(path, external_id + ".db")
self._db = PyDbLite.Base(filepath)
self._external_id = external_id
self._db.create("external_id", "command", "ts", mode="open")
def append(self, cmd):
self._db.insert(external_id=self._external_id, command=cmd, ts=datetime.now())
self._db.commit()
def match(self, command_prefix):
retults = [cmd for cmd in self._db if cmd["command"].startswith(command_prefix)]
return HistoryMatchList(command_prefix, [x["command"] for x in retults])
class ReplView(object):
def __init__(self, view, repl, syntax, repl_restart_args):
self.repl = repl
self._view = view
self._window = view.window()
self._repl_launch_args = repl_restart_args
# list of callable(repl) to handle view close events
self.call_on_close = []
#create writer queue and thread
self._work_queue = queue.Queue()
self.repl.set_ref("print_queue",self._work_queue)
self._worker = threading.Thread(target=self._write_worker)
self._worker.start()
if syntax:
view.set_syntax_file(syntax)
self._output_end = view.size()
self._prompt_size = 0
self._repl_reader = ReplReader(repl)
self._repl_reader.start()
settings = sublime.load_settings(SETTINGS_FILE)
view.settings().set("repl_external_id", repl.external_id)
view.settings().set("repl_id", repl.id)
view.settings().set("repl", True)
view.settings().set("repl_sublime2", SUBLIME2)
if repl.allow_restarts():
view.settings().set("repl_restart_args", repl_restart_args)
rv_settings = settings.get("repl_view_settings", {})
for setting, value in list(rv_settings.items()):
view.settings().set(setting, value)
view.settings().set("history_arrows", settings.get("history_arrows", True))
# for hysterical rasins ;)
persistent_history_enabled = settings.get("persistent_history_enabled") or settings.get("presistent_history_enabled")
if self.external_id and persistent_history_enabled:
self._history = PersistentHistory(self.external_id)
else:
self._history = MemHistory()
self._history_match = None
self._filter_color_codes = settings.get("filter_ascii_color_codes")
# optionally move view to a different group
# find current position of this replview
(group, index) = self._window.get_view_index(view)
# get the view that was focussed before the repl was opened.
# we'll have to focus this one briefly to make sure it's in the
# foreground again after moving the replview away
oldview = self._window.views_in_group(group)[max(0, index - 1)]
target = settings.get("open_repl_in_group")
# either the target group is specified by index
if isinstance(target, int):
if 0 <= target < self._window.num_groups() and target != group:
self._window.set_view_index(view, target, len(self._window.views_in_group(target)))
self._window.focus_view(oldview)
self._window.focus_view(view)
## or, if simply set to true, move it to the next group from the currently active one
elif target and group + 1 < self._window.num_groups():
self._window.set_view_index(view, group + 1, len(self._window.views_in_group(group + 1)))
self._window.focus_view(oldview)
self._window.focus_view(view)
#setup ANSI
self._view.run_command('hol_ansi')
# begin refreshing attached view
self.update_view_loop()
@property
def external_id(self):
return self.repl.external_id
def on_backspace(self):
if self.delta < 0:
self._view.run_command("left_delete")
def on_ctrl_backspace(self):
if self.delta < 0:
self._view.run_command("delete_word", {"forward": False, "sub_words": True})
def on_super_backspace(self):
if self.delta < 0:
for i in range(abs(self.delta)):
self._view.run_command("left_delete") # Hack to delete to BOL
def on_left(self):
if self.delta != 0:
self._window.run_command("move", {"by": "characters", "forward": False, "extend": False})
def on_shift_left(self):
if self.delta != 0:
self._window.run_command("move", {"by": "characters", "forward": False, "extend": True})
def on_home(self):
if self.delta > 0:
self._window.run_command("move_to", {"to": "bol", "extend": False})
else:
for i in range(abs(self.delta)):
self._window.run_command("move", {"by": "characters", "forward": False, "extend": False})
def on_shift_home(self):
if self.delta > 0:
self._window.run_command("move_to", {"to": "bol", "extend": True})
else:
for i in range(abs(self.delta)):
self._window.run_command("move", {"by": "characters", "forward": False, "extend": True})
def on_selection_modified(self):
self._view.set_read_only(self.delta > 0)
def on_close(self):
self.repl.close()
for fun in self.call_on_close:
fun(self)
def clear(self, edit):
self.escape(edit)
self._view.erase(edit, self.output_region)
self._output_end = self._view.sel()[0].begin()
def escape(self, edit):
self._view.set_read_only(False)
self._view.erase(edit, self.input_region)
self._view.show(self.input_region)
def enter(self):
v = self._view
if v.sel()[0].begin() != v.size():
v.sel().clear()
v.sel().add(sublime.Region(v.size()))
l = self._output_end
self.push_history(self.user_input) # don't include cmd_postfix in history
v.run_command("insert", {"characters": self.repl.cmd_postfix})
command = self.user_input
self.adjust_end()
if self.repl.apiv2:
self.repl.write(command, location=l)
else:
self.repl.write(command)
def previous_command(self, edit):
self._view.set_read_only(False)
self.ensure_history_match()
self.replace_current_input(edit, self._history_match.prev_command())
self._view.show(self.input_region)
def next_command(self, edit):
self._view.set_read_only(False)
self.ensure_history_match()
self.replace_current_input(edit, self._history_match.next_command())
self._view.show(self.input_region)
def update_view(self, view):
"""If projects were switched, a view could be a new instance"""
if self._view is not view:
self._view = view
def adjust_end(self):
if self.repl.suppress_echo:
v = self._view
vsize = v.size()
self._output_end = min(vsize, self._output_end)
v.run_command("hol_repl_erase_text", {"start": self._output_end, "end": vsize})
else:
self._output_end = self._view.size()
def write(self, unistr):
"""Writes output from Repl into this view."""
# remove color codes or remove from length count
if self._filter_color_codes:
unistr = re.sub(r'\033\[\d*(;\d*)?\w', '', unistr)
unistr = re.sub(r'.\x08', '', unistr)
self._work_queue.put(unistr)
def _write_worker(self):
while True:
unistr = self._work_queue.get()
if unistr is None:
break
# replace unsupported ansi escape codes before going forward: 2m 4m 5m 7m 8m
unsupported_pattern = r'\x1b\[(0;)?[24578]m'
str_data = re.sub(unsupported_pattern, "\x1b[1m", unistr)
# find ANSI codes
remove_pattern = r'(\x1b\[[0-9;]*m)+'
ansi_codes = re.finditer(remove_pattern, str_data)
ansi_codes = list(ansi_codes)
if ansi_codes:
# find all regions
ansi_regions = []
for ansi_def in ansi.ansi_definitions(str_data):
if re.search(ansi_def.regex, str_data):
reg = re.finditer(ansi_def.regex, str_data)
new_region = ansi.AnsiRegion(ansi_def.scope)
for m in reg:
new_region.add(*m.span())
ansi_regions.append(new_region)
# remove codes
ansi_codes.reverse()
for c in ansi_codes:
to_remove = c.span()
for r in ansi_regions:
r.cut_area(*to_remove)
out_data = re.sub(remove_pattern, "", str_data)
# create json serialable region representation
json_ansi_regions = {}
shift_val = self._view.size()
for region in ansi_regions:
region.shift(shift_val)
json_ansi_regions.update(region.jsonable())
else:
out_data = str_data
json_ansi_regions = None
# send on_data without ansi codes
self._view.run_command("hol_repl_insert_text", {"pos": self._view.size(), "text": out_data})
# send ansi command
if json_ansi_regions:
self._view.run_command('hol_ansi', args={"regions": json_ansi_regions})
self._output_end += len(out_data)
self._view.show(self.input_region)
def write_prompt(self, unistr):
"""Writes prompt from REPL into this view. Prompt is treated like
regular output, except output is inserted before the prompt."""
self._prompt_size = 0
self.write(unistr)
self._prompt_size = len(unistr)
def append_input_text(self, text, edit=None):
if edit:
self._view.insert(edit, self._view.size(), text)
else:
self._view.run_command("hol_repl_insert_text", {"pos": self._view.size(), "text": text})
def handle_repl_output(self):
"""Returns new data from Repl and bool indicating if Repl is still
working"""
try:
while True:
packet = self._repl_reader.queue.get_nowait()
if packet is None:
return False
self.handle_repl_packet(packet)
except queue.Empty:
return True
def handle_repl_packet(self, packet):
if self.repl.apiv2:
for opcode, data in packet:
if opcode == 'output':
self.write(data)
elif opcode == 'prompt':
self.write_prompt(data)
elif opcode == 'highlight':
a, b = data
regions = self._view.get_regions('sublimehol')
regions.append(sublime.Region(a, b))
self._view.add_regions('sublimehol', regions, 'invalid',
'', sublime.DRAW_EMPTY | sublime.DRAW_OUTLINED)
else:
print('HOL: unknown REPL opcode: ' + opcode)
else:
self.write(packet)
def update_view_loop(self):
is_still_working = self.handle_repl_output()
if is_still_working:
sublime.set_timeout(self.update_view_loop, 100)
else:
self.write("\n***Repl Killed***\n""" if self.repl._killed else "\n***Repl Closed***\n""")
self._view.set_read_only(True)
if sublime.load_settings(SETTINGS_FILE).get("view_auto_close"):
window = self._view.window()
if window is not None:
window.focus_view(self._view)
window.run_command("close")
def push_history(self, command):
self._history.push(command)
self._history_match = None
def ensure_history_match(self):
user_input = self.user_input
if self._history_match is not None:
if user_input != self._history_match.current_command():
# user did something! reset
self._history_match = None
if self._history_match is None:
self._history_match = self._history.match(user_input)
def replace_current_input(self, edit, cmd):
if cmd:
self._view.replace(edit, self.input_region, cmd)
self._view.sel().clear()
self._view.sel().add(sublime.Region(self._view.size()))
def run(self, edit, code):
self.replace_current_input(edit, code)
self.enter()
self._view.show(self.input_region)
self._window.focus_view(self._view)
@property
def view(self):
return self._view
@property
def input_region(self):
return sublime.Region(self._output_end, self._view.size())
@property
def output_region(self):
return sublime.Region(0, self._output_end - 2)
@property
def user_input(self):
"""Returns text entered by the user"""
return self._view.substr(self.input_region)
@property
def delta(self):
"""Return a repl_view and number of characters from current selection
to then begging of user_input (otherwise known as _output_end)"""
return self._output_end - self._view.sel()[0].begin()
def allow_deletion(self):
# returns true if all selections falls in user input
# and can be safetly deleted
output_end = self._output_end
for sel in self._view.sel():
if sel.begin() == sel.end() and sel.begin() == output_end:
# special case, when single selecion
# is at the very beggining of prompt
return False
# i don' really know if end() is always after begin()
if sel.begin() < output_end or sel.end() < output_end:
return False
return True
class ReplManager(object):
def __init__(self):
self.repl_views = {}
def repl_view(self, view):
repl_id = view.settings().get("repl_id")
if repl_id not in self.repl_views:
return None
rv = self.repl_views[repl_id]
rv.update_view(view)
return rv
def find_repl(self, external_id):
"""Yields rvews matching external_id taken from source.[external_id] scope
Match is done on external_id value of repl and additional_scopes"""
for rv in self.repl_views.values():
if not (rv.repl and rv.repl.is_alive()):
continue # dead repl, skip
rvid = rv.external_id
additional_scopes = rv.repl.additional_scopes
if rvid == external_id or external_id in additional_scopes:
yield rv
def open(self, window, encoding, type, syntax=None, view_id=None, **kwds):
repl_restart_args = {
'encoding': encoding,
'type': type,
'syntax': syntax,
}
repl_restart_args.update(kwds)
try:
kwds = ReplManager.translate(window, kwds)
encoding = ReplManager.translate(window, encoding)
r = repls.Repl.subclass(type)(encoding, **kwds)
found = None
for view in window.views():
if view.id() == view_id:
found = view
break
view = found or window.new_file()
rv = ReplView(view, r, syntax, repl_restart_args)
rv.call_on_close.append(self._delete_repl)
self.repl_views[r.id] = rv
view.set_scratch(True)
view.set_name("*REPL* [%s]" % (r.name(),))
return rv
except Exception as e:
traceback.print_exc()
sublime.error_message(repr(e))
def restart(self, view, edit):
repl_restart_args = view.settings().get("repl_restart_args")
if not repl_restart_args:
sublime.message_dialog("No restart parameters found")
return False
rv = self.repl_view(view)
if rv:
if rv.repl and rv.repl.is_alive() and not sublime.ok_cancel_dialog("Still running. Really restart?"):
return False
rv.on_close() # yes on_close, delete rv from
view.insert(edit, view.size(), RESTART_MSG)
repl_restart_args["view_id"] = view.id()
self.open(view.window(), **repl_restart_args)
return True
def _delete_repl(self, repl_view):
repl_id = repl_view.repl.id
if repl_id not in self.repl_views:
return None
del self.repl_views[repl_id]
@staticmethod
def translate(window, obj, subst=None):
if subst is None:
subst = ReplManager._subst_for_translate(window)
if isinstance(obj, dict):
return ReplManager._translate_dict(window, obj, subst)
if isinstance(obj, unicode_type): # PY2
return ReplManager._translate_string(window, obj, subst)
if isinstance(obj, list):
return ReplManager._translate_list(window, obj, subst)
return obj
@staticmethod
def _subst_for_translate(window):
""" Return all available substitutions"""
import locale
res = {
"packages": sublime.packages_path(),
"installed_packages": sublime.installed_packages_path()
}
if window.folders():
res["folder"] = window.folders()[0]
res["editor"] = "subl -w"
res["win_cmd_encoding"] = "utf8"
if sublime.platform() == "windows":
res["win_cmd_encoding"] = locale.getdefaultlocale()[1]
res["editor"] = '"%s"' % (sys.executable,)
av = window.active_view()
if av is None:
return res
filename = av.file_name()
if not filename:
return res
filename = os.path.abspath(filename)
res["file"] = filename
res["file_path"] = os.path.dirname(filename)
res["file_basename"] = os.path.basename(filename)
if 'folder' not in res:
res["folder"] = res["file_path"]
if sublime.load_settings(SETTINGS_FILE).get("use_build_system_hack", False):
project_settings = sublimehol_build_system_hack.get_project_settings(window)
res.update(project_settings)
return res
@staticmethod
def _translate_string(window, string, subst=None):
from string import Template
if subst is None:
subst = ReplManager._subst_for_translate(window)
# see #200, on older OSX (10.6.8) system wide python won't accept
# dict(unicode -> unicode) as **argument.
# It's best to just str() keys, since they are ascii anyway
if PY2:
subst = dict((str(key), val) for key, val in subst.items())
return Template(string).safe_substitute(**subst)
@staticmethod
def _translate_list(window, list, subst=None):
if subst is None:
subst = ReplManager._subst_for_translate(window)
return [ReplManager.translate(window, x, subst) for x in list]
@staticmethod
def _translate_dict(window, dictionary, subst=None):
if subst is None:
subst = ReplManager._subst_for_translate(window)
if PLATFORM in dictionary:
return ReplManager.translate(window, dictionary[PLATFORM], subst)
for k, v in list(dictionary.items()):
dictionary[k] = ReplManager.translate(window, v, subst)
return dictionary
manager = ReplManager()
# Window Commands #########################################
# Opens a new REPL
class HolReplOpenCommand(sublime_plugin.WindowCommand):
def run(self, encoding, type, syntax=None, view_id=None, **kwds):
manager.open(self.window, encoding, type, syntax, view_id, **kwds)
class HolReplRestartCommand(sublime_plugin.TextCommand):
def run(self, edit):
manager.restart(self.view, edit)
def is_visible(self):
if not self.view:
return False
return bool(self.view.settings().get("repl_restart_args", None))
def is_enabled(self):
return self.is_visible()
# REPL Comands ############################################
# Submits the Command to the REPL
class HolReplEnterCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.enter()
class HolReplClearCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.clear(edit)
# Resets HolRepl Command Line
class HolReplEscapeCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.escape(edit)
def repl_view_delta(sublime_view):
"""Return a repl_view and number of characters from current selection
to then beggingin of user_input (otherwise known as _output_end)"""
rv = manager.repl_view(sublime_view)
if not rv:
return None, -1
delta = rv._output_end - sublime_view.sel()[0].begin()
return rv, delta
class HolReplBackspaceCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.on_backspace()
class HolReplCtrlBackspaceCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.on_ctrl_backspace()
class HolReplSuperBackspaceCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.on_super_backspace()
class HolReplLeftCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.on_left()
class HolReplShiftLeftCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.on_shift_left()
class HolReplHomeCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.on_home()
class HolReplShiftHomeCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.on_shift_home()
class HolReplViewPreviousCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.previous_command(edit)
class HolReplViewNextCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.next_command(edit)
class HolReplKillCommand(sublime_plugin.TextCommand):
def run(self, edit):
rv = manager.repl_view(self.view)
if rv:
rv.repl.kill()
def is_visible(self):
rv = manager.repl_view(self.view)
return bool(rv)
def is_enabled(self):
return self.is_visible()
class SublimeHOLListener(sublime_plugin.EventListener):
def on_selection_modified(self, view):
rv = manager.repl_view(view)
if rv and not view.settings().get("hol_ansi_in_progress", False):
rv.on_selection_modified()
def on_close(self, view):
rv = manager.repl_view(view)
if rv:
rv.on_close()
def on_text_command(self, view, command_name, args):
rv = manager.repl_view(view)
if not rv:
return None
if command_name == 'left_delete':
# stop backspace on ST3 w/o breaking brackets
if not rv.allow_deletion():
return 'hol_repl_pass', {}
if command_name == 'delete_word' and not args.get('forward'):
# stop ctrl+backspace on ST3 w/o breaking brackets
if not rv.allow_deletion():
return 'hol_repl_pass', {}
return None
class HolSubprocessReplSendSignal(sublime_plugin.TextCommand):
def run(self, edit, signal=None):
rv = manager.repl_view(self.view)
subrepl = rv.repl
signals = subrepl.available_signals()
sorted_names = sorted(signals.keys())
if signal in signals:
#signal given by name
self.safe_send_signal(subrepl, signals[signal])
return
if signal in list(signals.values()):
#signal given by code (correct one!)
self.safe_send_signal(subrepl, signal)
return
# no or incorrect signal given
def signal_selected(num):
if num == -1:
return
signame = sorted_names[num]
sigcode = signals[signame]
self.safe_send_signal(subrepl, sigcode)
self.view.window().show_quick_panel(sorted_names, signal_selected)
def safe_send_signal(self, subrepl, sigcode):
try:
subrepl.send_signal(sigcode)
except Exception as e:
sublime.error_message(str(e))
def is_visible(self):
rv = manager.repl_view(self.view)
return bool(rv) and hasattr(rv.repl, "send_signal")
def is_enabled(self):
return self.is_visible()
def description(self):
return "Send SIGNAL"