-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexternal_programs.py
1007 lines (776 loc) · 33.4 KB
/
external_programs.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
""" Run an external program on the current file, file URI, text URI, selection
or nothing, pass the data to the program via a single argument, its standard
input stream, or nothing, write back the result from the program taken from
its standard output stream, inserted at the caret, written as a replacement of
the selected text, to an output panel, or to nothing. Provide a work-around
for `exec` from `*.sublime-commands` files.
See [README](README.md).
Limitations:
* Change to the "output_panel_name" setting, requires a restart.
* Change to the "errors_panel_name" setting, requires a restart.
"""
import os.path
import sublime
import sublime_plugin
import subprocess
import urllib.parse
import html
import random
import tempfile
import _thread
PREFERENCES_FILE = "Preferences.sublime-settings"
SETTINGS_FILE = "External_Programs.sublime-settings"
PREFERENCES = None # Initialized by `plugin_loaded`
SETTINGS = None # Initialized by `plugin_loaded`
# External_Program
# ============================================================================
# Main entry point is `run`
#
#
# Settings are handled by:
#
# * `ERRORS_PANEL_NAME`
# * `OUTPUT_PANEL_NAME`
# * `get_timeout_delay`
#
#
# Parameters are interpreted by:
#
# * `get_output_method` for `destination`
# * `get_invokation_method` for `executable`
# * `setup_panels` for `panels`
# * `get_input` for `source`
# * `get_invokation_method` for `through`
#
#
# Parameter values are handled by:
#
# * `get_insert_replace_writer` for `destination:insert_replace`
# * `get_nothing_writer` for `destination` not set
# * `get_output_panel_writer` for `destination:output_panel`
# * `get_phantom_writer` for `destination:phantom`
# * `setup_panels` it-self for `panels:accumulate`
# * `erase_view_content` for `panels:reset`
# * `get_file_name` for `source:file_name`
# * `get_file_uri` for `source:file_uri`
# * `get_input` it-self for `source` not set
# * `get_selected_text` for `source:selected_text`
# * `get_text_uri` for `source:text_uri`
# * `invoke_using_nothing` for `though` not set
# * `invoke_using_single_argument` for `though:single_argument`
# * `invoke_using_stdin` for `though:stdin`
# Default when no settings found
# ----------------------------------------------------------------------------
DEFAULT_ERRORS_PANEL_NAME = "errors"
DEFAULT_OUTPUT_PANEL_NAME = "output"
DEFAULT_TIMEOUT_DELAY = 3 # Seconds, not milliseconds.
# String constants from Sublime Text
# ----------------------------------------------------------------------------
S_CHARACTERS = "characters"
S_INSERT = "insert"
S_PANEL = "panel"
S_SHOW_PANEL = "show_panel"
# String constants defined for this command
# ----------------------------------------------------------------------------
S_ACCUMULATE = "accumulate"
S_ERRORS_PANEL_NAME = "errors_panel_name"
S_FILE_NAME = "file_name"
S_FILE_URI = "file_uri"
S_INSERT_REPLACE = "insert_replace"
S_OUTPUT_PANEL = "output_panel"
S_OUTPUT_PANEL_NAME = "output_panel_name"
S_PANEL_SYNTAX = "panel_syntax"
S_PANEL_FILE_REGEX = "panel_file_regex"
S_PANEL_LINE_REGEX = "panel_line_regex"
S_PANEL_WORD_WRAP = "panel_word_wrap"
S_PHANTOM = "phantom"
S_RESET = "reset"
S_SELECTED_TEXT = "selected_text"
S_SINGLE_ARGUMENT = "single_argument"
S_TEMPORARY_FILE = "temporary_file"
S_STDIN = "stdin"
S_TEXT_URI = "text_uri"
S_TIMEOUT_DELAY = "timeout_delay"
# Constants from settings
# ----------------------------------------------------------------------------
ERRORS_PANEL_NAME = None # Initialized by `plugin_loaded`
OUTPUT_PANEL_NAME = None # Initialized by `plugin_loaded`
# The class
# ----------------------------------------------------------------------------
class ExternalProgramCommand(sublime_plugin.TextCommand):
""" Integration of external program, mainly as text command.
See [README](README.md) on section `external_program`.
"""
BUSY = False
DESTINATION = None
ERRORS_PANEL = None
OUTPUT_PANEL = None
def __init__(self, arg2):
""" Just invoke the parent class constructor. """
super().__init__(arg2)
# ### Main
def errors_panel(self):
""" Return the single instance of the panel for errors output.
The panel is created on the first invocation.
"""
cls = type(self)
if cls.ERRORS_PANEL is None:
window = self.view.window()
cls.ERRORS_PANEL = window.create_output_panel(ERRORS_PANEL_NAME)
self.configure_panel(cls.ERRORS_PANEL)
result = cls.ERRORS_PANEL
return result
def output_panel(self):
""" Return the single instance of the panel for “normal” output.
The panel is created on the first invocation.
"""
if self.OUTPUT_PANEL is None:
window = self.view.window()
self.OUTPUT_PANEL = window.create_output_panel(OUTPUT_PANEL_NAME)
self.configure_panel(self.OUTPUT_PANEL)
result = self.OUTPUT_PANEL
return result
def configure_panel(self, panel):
if SETTINGS.get(S_PANEL_SYNTAX):
panel.assign_syntax(SETTINGS.get(S_PANEL_SYNTAX))
if SETTINGS.get(S_PANEL_FILE_REGEX):
panel.settings().set("result_file_regex", SETTINGS.get(S_PANEL_FILE_REGEX))
if SETTINGS.get(S_PANEL_LINE_REGEX):
panel.settings().set("result_line_regex", SETTINGS.get(S_PANEL_LINE_REGEX))
panel.settings().set("word_wrap", SETTINGS.get(S_PANEL_WORD_WRAP, True))
panel.settings().set("line_numbers", False)
panel.settings().set("gutter", False)
panel.settings().set("scroll_past_end", False)
def write_error(self, text):
""" Write `text` to the errors panel and shows it. """
errors_panel = self.errors_panel()
errors_panel.run_command("run_external_program", {
"regions": [[errors_panel.size(), errors_panel.size()]], # this means appending
"results": [text],
"clear_selection": True,
})
window = self.view.window()
window.run_command(
S_SHOW_PANEL,
{S_PANEL: "output.%s" % ERRORS_PANEL_NAME})
@staticmethod
def erase_view_content(view):
""" Erase all text in `view`. """
region = sublime.Region(0, view.size())
view.sel().add(region)
view.run_command(S_INSERT, {S_CHARACTERS: ""})
def setup_panels(self, panels):
""" Handle the `panels` argument to `external_command`.
If the `panels` value is invalid, don't treat as error,
and use the default instead (`reset`).
"""
if panels == S_ACCUMULATE:
# Keep their content
pass
else:
self.erase_view_content(self.output_panel())
self.erase_view_content(self.errors_panel())
# See also `get_output_panel_writer`.
# Input (text content passed to invoked program)
# ------------------------------------------------------------------------
# ### Helper
def get_text_fragment_identifier(self):
""" Return a character position or range identifier after RFC 5147.
The identifier returned contains the `#` prefix and if if there is no
selection, return an empty string, so that the result can be directly
appended to an URI.
Display an error in the status bar and return `None`, in case of
multiple selection.
"""
result = None
view = self.view
sel = view.sel()
if len(sel) == 0:
result = ""
elif len(sel) > 1:
sublime.status_message("Error: multiple selections")
else:
region = sel[0]
if region.empty():
result = "#char=%i" % region.a
else:
result = "#char=%i,%i" % (region.a, region.b)
return result
# ### Main
def get_file_name(self):
""" Return the simple file name of the active file or `None`.
If there is no active file for the active view, additionally to
returning `None`, display an error message in the status bar.
This is to be the argument passed to the invoked program, when
`source` is `file_name`.
"""
result = None
view = self.view
file = view.file_name()
if file is None:
sublime.status_message("Error: no file")
else:
result = os.path.split(file)[1]
return result
def get_file_uri(self):
""" Return the URI of the active file or `None`.
If there is no active file for the active view, additionally to
returning `None`, display an error message in the status bar.
This is to be the argument passed to the invoked program, when
`source` is `file_uri`.
"""
result = None
view = self.view
file = view.file_name()
if file is None:
sublime.status_message("Error: no file")
else:
path = os.path.abspath(file)
path = urllib.parse.quote(path)
result = "file://%s" % path
return result
def get_text_uri(self):
""" Return text URI of selection in the active file or `None`.
If there is no selection, the result is the same as the file URI. The
fragment identifier is from `get_text_fragment_identifier`.
If there is no active file or a multiple selection, display an error
message in the status bar.
This is to be the argument passed to the invoked program, when
`source` is `text_uri`.
"""
file_uri = self.get_file_uri()
if file_uri is not None:
text_fid = self.get_text_fragment_identifier()
if text_fid is not None:
result = file_uri + text_fid
return result
def get_selected_text(self):
""" Return the text in the current selection or `None`.
If there is no selection, a multiple selection or the selection is
empty, for the active window, additionally to returning `None`,
display an error message in the status bar.
This is to be the argument passed to the invoked program, when
`source` is `selected_text`.
"""
result = None
view = self.view
sel = view.sel()
if len(sel) == 0:
sublime.status_message("Error: no selection")
elif len(sel) > 1:
sublime.status_message("Error: multiple selections")
else:
region = sel[0]
if region.empty():
region = sublime.Region(0, view.size())
result = view.substr(region)
return result
def get_input(self, source):
""" Return the text to be passed to the program or `None`.
If `source` is unknown, additionally to returning `None`, display an
error message in the status bar.
This method handles the `source` argument to `external_command`.
"""
result = None
if source == S_SELECTED_TEXT:
result = self.get_selected_text()
elif source == S_FILE_NAME:
result = self.get_file_name()
elif source == S_FILE_URI:
result = self.get_file_uri()
elif source == S_TEXT_URI:
result = self.get_text_uri()
elif source is None:
result = ""
else:
sublime.status_message(
"Error: unknown source `%s`"
% source)
return result
# Output (how to write text returned by invoked program)
# ------------------------------------------------------------------------
def get_insert_replace_writer(self, source):
""" Return a method to write to the current selection or `None`.
If there is no selection or a multiple selection, additionally to
returning `None`, display an error message in the status bar.
The method returned expects a single `text` argument.
This is the method to be used when `destination` is `insert_replace`.
The selection may be empty, in which case it ends to be an “insert”,
otherwise, it ends to be a “replace”.
"""
result = None
view = self.view
sel = view.sel()
if len(sel) == 0:
sublime.status_message("Error: no selection")
elif len(sel) > 1:
sublime.status_message("Error: multiple selections")
else:
region = sel[0]
if region.empty() and source == S_SELECTED_TEXT:
region = sublime.Region(0, view.size())
def writer(text):
view.run_command("run_external_program", {
"regions": [[region.begin(), region.end()]],
"results": [text],
})
return writer
def get_output_panel_writer(self):
""" Return a method to write to the output panel.
The method returned expects a single `text` argument.
This is the method to be used when `destination` is `output_panel`.
"""
def write_output(text):
""" Write `text` to the output panel and shows it. """
output_panel = self.output_panel()
output_panel.run_command("run_external_program", {
"regions": [[output_panel.size(), output_panel.size()]], # this means appending
"results": [text],
"clear_selection": True,
})
window = self.view.window()
window.run_command(
S_SHOW_PANEL,
{S_PANEL: "output.%s" % OUTPUT_PANEL_NAME})
result = write_output
return result
def get_phantom_writer(self):
""" Return a method to write to a phantom.
The method returned expects a single `text` argument.
This is the method to be used when `destination` is `phantom`.
"""
def write_output(text):
""" Write `text` to a phantom. """
style = '''
<style>
html.dark {
background-color: var(--yellowish);
}
html.light {
background-color: #88db7d;
}
body {
padding-right: 1rem;
color: black;
}
.hide {
color: black;
text-decoration: none;
}
</style>
'''
html_content = (
"<body id='external-programs'>"
+ style
+ "<a class='hide' href='hide'> " + chr(0x00D7) + " </a> "
+ "<span class='command-output'>"
+ html.escape(text.strip()).replace("\n", "<br>")
+ "</span>"
+ "</body>"
)
phantom_id = str(random.randrange(1, 1000000))
region_end = self.view.sel()[0].end()
self.view.add_phantom(
# Sublime Text Phantom API doesn't provide a native mechanism to
# hide a single phantom. In order to emulate that feature, we use
# unique keys as "phantom set" key for each phantom and later use
# that key to hide a particular phantom.
"external_programs/" + phantom_id,
# Make sure that the phantom is always displayed at the bottom of a
# multi-line selection.
sublime.Region(region_end, region_end),
html_content,
sublime.LAYOUT_BLOCK,
on_navigate = self.get_phantom_navigate_method(phantom_id))
return write_output
def get_phantom_navigate_method(self, phantom_id):
def on_phantom_navigate(url):
if url == "hide":
self.view.erase_phantoms("external_programs/" + phantom_id)
return on_phantom_navigate
@staticmethod
def get_nothing_writer():
""" Return a method to write nothing.
The method returned expects a single `text` argument (which is
ignored).
This is the method to be used when `destination` is not set.
"""
result = lambda text: None
return result
def get_output_method(self, source, destination):
""" Return the method to write the program result or `None`.
If `destination` is unknown, additionally to returning `None`, display
an error message in the status bar.
The method returned expects a single `text` argument.
This method handles the `destination` argument to `external_command`.
"""
result = None
if destination == S_INSERT_REPLACE:
result = self.get_insert_replace_writer(source)
elif destination == S_OUTPUT_PANEL:
result = self.get_output_panel_writer()
elif destination == S_PHANTOM:
result = self.get_phantom_writer()
elif destination is None:
result = self.get_nothing_writer()
else:
sublime.status_message(
"Error: unknown destination `%s`"
% destination)
return result
# Process
# ------------------------------------------------------------------------
# ### Helpers
@staticmethod
def get_timeout_delay():
""" Return timeout delay after settings or else a default. """
result = SETTINGS.get(S_TIMEOUT_DELAY, DEFAULT_TIMEOUT_DELAY)
return result
def get_working_directory(self):
""" Return the directory of the active file or `None`.
This is the directory to be used as the working directory of the
invoked program.
"""
result = None
view = self.view
file = view.file_name()
if file is not None:
result = os.path.split(file)[0]
return result
# ### Main
@classmethod
def get_invokation_method(cls, executable, directory, through, output, destination):
""" Return the method to invoke the program or `None`.
If `through` is unknown, additionally to returning `None`, display an
error message in the status bar.
This method handles the `through` argument to `external_command` and
articulates the overall invocation process.
The method depends on the way the parameter is passed to the program
to be invoked.
The method returned expects a single `text` argument and returns a
triplet `(stdout, stderr, return_code)` where `stdout` and `stderr`
are strings content returned by the program on these streams and
`return_code` is the integer status returned by the program. If an
error occurs (not from the program), the method returns both `stdout`
and `return_code` set to `None`, however, `stderr` is still a string,
as indeed, if the program was stopped due to a time-out, it may have
sent something to `stderr` (however, `stdout` is then to be ignored,
and that's why it is set to `None`).
In case of error, the method returned, will write an error message to
the status bar.
"""
timeout_delay = cls.get_timeout_delay()
# #### Exception handling
def on_error(error, process):
""" Handle `OSError` and `TimeoutExpired`, returning `stderr`.
If no `stderr` content can be returned, return an empty string.
Write an error message to the status bar, as much as possible.
"""
stderr = ""
try:
raise error
except OSError:
message = "Error: Could not run command."
except subprocess.TimeoutExpired as timeout:
stderr = getattr(timeout, "stderr", "")
process.kill()
(_stdout, stderr_tail) = process.communicate()
stderr += stderr_tail.decode("utf-8")
message = "Error: Command takes too long."
except Exception as err: # pylint: disable=bare-except
message = "Error while attempting to run command: " + repr(err)
print(message);
sublime.status_message(message);
return stderr
# #### Methods
def invoke_using_stdin(text):
""" Invoke the program with `text` passed through its `stdin`.
Return `(stdout, stderr, return_code)`.
"""
try:
print("Executing: %s" % executable)
process = subprocess.Popen(
executable,
cwd=directory,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(stdout, stderr) = process.communicate(
input=text.encode("utf-8"),
timeout=timeout_delay)
stdout = stdout.decode("utf-8")
stderr = stderr.decode("utf-8")
result = (stdout, stderr, process.returncode)
except Exception as error: # pylint: disable=broad-except
result = (None, on_error(error, process), None)
return result
def invoke_using_single_argument(text):
""" Invoke the program with `text` passed as a single argument.
Return `(stdout, stderr, return_code)`.
"""
try:
executable.append(text)
print("Executing: %s" % executable)
process = subprocess.Popen(
executable,
cwd=directory,
shell=True,
stdin=None,
stdout = None if destination is None else subprocess.PIPE,
stderr = None if destination is None else subprocess.PIPE)
if destination is not None:
(stdout, stderr) = process.communicate(timeout=timeout_delay)
stdout = stdout.decode("utf-8")
stderr = stderr.decode("utf-8")
result = (stdout, stderr, process.returncode)
else:
# It's probably a GUI application. We're not interested in the output.
result = ("", "", 0)
except Exception as error: # pylint: disable=broad-except
result = (None, on_error(error, process), None)
return result
def invoke_using_temporary_file(text):
""" Save the `text` to a temporary file and invoke the program with its
path passed as a single argument.
Return `(output_text, stderr, return_code)`.
"""
try:
with tempfile.NamedTemporaryFile(mode = "w+", dir = sublime.packages_path(), prefix = "external-programs-", suffix = ".temp", delete = False, encoding = "utf-8", newline = "") as file:
file.write(text)
file.close()
executable.append(file.name)
print("Executing: %s" % executable)
process = subprocess.Popen(
executable,
cwd = directory,
shell = True,
stdin = None,
stdout = None if destination is None else subprocess.PIPE,
stderr = None if destination is None else subprocess.PIPE)
if destination is not None:
(stdout, stderr) = process.communicate(timeout = timeout_delay)
stdout = stdout.decode("utf-8")
stderr = stderr.decode("utf-8")
if output == "temporary_file":
output_text = open(file.name, "r", encoding = "utf-8", newline = "").read()
if stdout:
print(stdout)
else:
output_text = stdout
result = (output_text, stderr, process.returncode)
else:
# It's probably a GUI application. We're not interested in the output.
result = ("", "", 0)
except Exception as error: # pylint: disable=broad-except
result = (None, on_error(error, process), None)
finally:
if os.path.isfile(file.name):
os.unlink(file.name)
return result
def invoke_using_nothing(ignore):
""" Invoke the program with nothing (no argument, no input).
Return `(stdout, stderr, return_code)`.
"""
try:
print("Executing: %s" % executable)
process = subprocess.Popen(
executable,
cwd=directory,
shell=True,
stdin=None,
stdout = None if destination is None else subprocess.PIPE,
stderr = None if destination is None else subprocess.PIPE)
if destination is not None:
(stdout, stderr) = process.communicate(timeout=timeout_delay)
stdout = stdout.decode("utf-8")
stderr = stderr.decode("utf-8")
result = (stdout, stderr, process.returncode)
else:
# It's probably a GUI application. We're not interested in the output.
result = ("", "", 0)
except Exception as error: # pylint: disable=broad-except
result = (None, on_error(error, process), None)
return result
# #### Main
if through == S_STDIN:
result = invoke_using_stdin
elif through == S_SINGLE_ARGUMENT:
result = invoke_using_single_argument
elif through == S_TEMPORARY_FILE:
result = invoke_using_temporary_file
elif through is None:
result = invoke_using_nothing
else:
result = None
sublime.status_message(
"Error: unknown channel `%s`"
% through)
return result
def selection_exists(self):
for region in self.view.sel():
if not region.empty():
return True
return False
# Main
# ------------------------------------------------------------------------
def run(self,
edit,
executable,
source = None,
through = None,
output = "stdout",
destination = None,
panels=S_RESET):
""" Invoke `executable` as specified by the next three parameters.
In case of error(s), write an error message to the status bar.
Return nothing.
"""
cls = type(self)
directory = self.get_working_directory()
# Parameters interpretation begin
self.setup_panels(panels)
if not type(executable) is list:
executable = [executable]
# Expand special variables. See: http://www.sublimetext.com/docs/3/build_systems.html#variables
variables = self.view.window().extract_variables()
executable = [sublime.expand_variables(value, variables) for value in executable]
if source is None:
through = None
if destination is None:
output = None
cls.DESTINATION = destination
input = self.get_input(source)
invoke_method = self.get_invokation_method(executable, directory, through, output, destination)
output_method = self.get_output_method(source, destination)
# Parameters interpretation end
if cls.BUSY:
sublime.status_message("Error: busy")
elif None not in [input, invoke_method, output_method]:
cls.BUSY = True
# Core thread
def thread():
(result, stderr, return_code) = invoke_method(input)
# Check if the program is aborted.
if not cls.BUSY:
return
# Sometimes commands may return an output with a trailing newline. If
# the input also has a trailing newline then we accept the one in the
# output, otherwise remove it.
if result is not None and not input.endswith("\n") and self.selection_exists():
result = result.rstrip("\n")
messages = []
if destination == "insert_replace":
if result:
output_method(result)
else:
messages.append("Empty output.")
else:
output_method(result or "[no output]")
if return_code is not None:
messages.append("Return code: %i" % return_code)
if messages:
sublime.status_message(" ".join(messages));
if stderr != "":
print(stderr)
self.write_error(stderr)
self.write_error("\n")
cls.BUSY = False
_thread.start_new_thread(thread, ())
# Source: https://github.com/greneholt/SublimeExternalCommand
def spin(size, i=0, addend=1):
if not cls.BUSY:
self.view.erase_status("external_programs")
return
before = i % size
after = (size - 1) - before
self.view.set_status("external_programs", "%s [%s=%s]" % (executable[0], " " * before, " " * after))
if not after:
addend = -1
if not before:
addend = 1
i += addend
sublime.set_timeout(lambda: spin(size, i, addend), 100)
spin(8)
@staticmethod
def description():
""" Return a long sentence as a description. """
return (
"Typically, run an external command receiving the current "
"selection on standard input and replace the current selection "
"with what it writes on standard output.")
# Helper command for putting the output of the external program back into the
# buffer. This is needed beacuse of the usage of thread. Sublime Text doesn't
# preserve `edit` object in a thread (such as `view.replace(edit, region, text)`),
# because the main command is already completed.
class RunExternalProgramCommand(sublime_plugin.TextCommand):
def run(self, edit, regions, results, clear_selection=False):
for region, result in zip(reversed(regions), reversed(results)):
self.view.replace(edit, sublime.Region(region[0], region[1]), result)
if clear_selection:
self.view.sel().clear()
def is_visible(self):
return False
class ExternalProgramListener(sublime_plugin.EventListener):
def abort_program(self):
if ExternalProgramCommand.BUSY:
ExternalProgramCommand.BUSY = False
sublime.status_message("Program aborted.");
def on_modified(self, view):
if ExternalProgramCommand.DESTINATION == "insert_replace":
self.abort_program()
def on_selection_modified(self, view):
if ExternalProgramCommand.DESTINATION == "insert_replace":
self.abort_program()
def on_close(self, view):
self.abort_program()
def __del__(self):
self.abort_program()
# Helper commands
# ----------------------------------------------------------------------------
# ### `external_program_show_errors`
class ExternalProgramShowErrors(sublime_plugin.WindowCommand):
""" Command to show the errors panel. """
def __init__(self, arg2):
""" Just invoke the parent class constructor. """
super().__init__(arg2)
def run(self):
""" Show the errors panel. """
if ExternalProgramCommand.ERRORS_PANEL is not None:
self.window.run_command(
S_SHOW_PANEL,
{S_PANEL: "output.%s" % ERRORS_PANEL_NAME})
else:
sublime.status_message("No errors output so far.")
# ### `external_program_show_output`
class ExternalProgramShowOutput(sublime_plugin.WindowCommand):
""" Command to show the output panel. """
def __init__(self, arg2):
""" Just invoke the parent class constructor. """
super().__init__(arg2)
def run(self):
""" Show the output panel. """
if ExternalProgramCommand.OUTPUT_PANEL is not None:
self.window.run_command(
S_SHOW_PANEL,
{S_PANEL: "output.%s" % OUTPUT_PANEL_NAME})
else:
sublime.status_message("No output result so far.")
# Load-time
# ============================================================================
def plugin_loaded():
""" Initialize globals which can't be initialized at module load-time. """
# Sorry, PyLint, there is no other way.
# pylint: disable=global-statement
global ERRORS_PANEL_NAME
global OUTPUT_PANEL_NAME
global PREFERENCES
global SETTINGS
PREFERENCES = sublime.load_settings(PREFERENCES_FILE)
SETTINGS = sublime.load_settings(SETTINGS_FILE)