|
1 | | -import sublime, sublime_plugin, subprocess |
| 1 | +import os |
| 2 | +import sublime |
| 3 | +import sublime_plugin |
| 4 | +import subprocess |
2 | 5 |
|
3 | 6 | class MixFormatFileCommand(sublime_plugin.TextCommand): |
4 | 7 | def run(self, edit): |
5 | 8 | window = self.view.window() |
6 | 9 | window.run_command("save") |
| 10 | + window.run_command("mix_format_file_without_save") |
7 | 11 |
|
8 | | - cmd = ["mix", "format", self.view.file_name()] |
9 | | - cwd = window.folders()[0] |
10 | | - returncode = subprocess.call(cmd, cwd=cwd) |
| 12 | +class MixFormatOnSave(sublime_plugin.EventListener): |
| 13 | + def on_post_save(self, view): |
| 14 | + sel = view.sel()[0] |
| 15 | + region = view.word(sel) |
| 16 | + scope = view.scope_name(region.b) |
11 | 17 |
|
12 | | - if returncode == 0: |
13 | | - window.status_message("Formatting successful!") |
| 18 | + if scope.find('source.elixir') != -1: |
| 19 | + settings = sublime.load_settings('Elixir.sublime-settings') |
| 20 | + |
| 21 | + if settings.get('mix_format_on_save', False): |
| 22 | + view.run_command('mix_format_file_without_save') |
| 23 | + |
| 24 | +class MixFormatFileWithoutSaveCommand(sublime_plugin.TextCommand): |
| 25 | + def run(self, edit): |
| 26 | + window = self.view.window() |
| 27 | + |
| 28 | + # Hide the console window on Windows |
| 29 | + shell = False |
| 30 | + path_separator = ':' |
| 31 | + if os.name == 'nt': |
| 32 | + shell = True |
| 33 | + path_separator = ';' |
| 34 | + |
| 35 | + cmd = ['mix', 'format', self.view.file_name()] |
| 36 | + |
| 37 | + p = subprocess.Popen( |
| 38 | + cmd, |
| 39 | + stdout=subprocess.PIPE, |
| 40 | + stderr=subprocess.PIPE, |
| 41 | + shell=shell |
| 42 | + ) |
| 43 | + |
| 44 | + _, stderrdata = p.communicate() |
| 45 | + |
| 46 | + stderrdata = stderrdata.strip() |
| 47 | + |
| 48 | + if stderrdata: |
| 49 | + panel_view = window.create_output_panel('mix_format') |
| 50 | + panel_view.set_read_only(False) |
| 51 | + |
| 52 | + panel_view.run_command('erase_view') |
| 53 | + panel_view.run_command('append', {'characters': stderrdata.decode()}) |
| 54 | + |
| 55 | + panel_view.set_read_only(True) |
| 56 | + window.run_command('show_panel', {'panel': 'output.mix_format'}) |
14 | 57 | else: |
15 | | - # TODO: Ideally we would show errors in a pane but life |
16 | | - # is too short to figure it out. Pull requests welcome! |
17 | | - sublime.error_message("Formatting failed!") |
| 58 | + window.run_command('hide_panel', {'panel': 'output.mix_format'}) |
| 59 | + window.status_message('Formatting successful!') |
| 60 | + |
| 61 | + |
0 commit comments