| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
from __future__ import absolute_import, division, print_function |
| 16 |
import sublime |
| 17 |
import sublime_plugin |
| 18 |
import subprocess |
| 19 |
|
| 20 |
|
| 21 |
binary = 'clang-format' |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
style = None |
| 28 |
|
| 29 |
class ClangFormatCommand(sublime_plugin.TextCommand): |
| 30 |
def run(self, edit): |
| 31 |
encoding = self.view.encoding() |
| 32 |
if encoding == 'Undefined': |
| 33 |
encoding = 'utf-8' |
| 34 |
regions = [] |
| 35 |
command = [binary] |
| 36 |
if style: |
| 37 |
command.extend(['-style', style]) |
| 38 |
for region in self.view.sel(): |
| 39 |
regions.append(region) |
| 40 |
region_offset = min(region.a, region.b) |
| 41 |
region_length = abs(region.b - region.a) |
| 42 |
command.extend(['-offset', str(region_offset), |
| 43 |
'-length', str(region_length), |
| 44 |
'-assume-filename', str(self.view.file_name())]) |
| 45 |
old_viewport_position = self.view.viewport_position() |
| 46 |
buf = self.view.substr(sublime.Region(0, self.view.size())) |
| 47 |
p = subprocess.Popen(command, stdout=subprocess.PIPE, |
| 48 |
stderr=subprocess.PIPE, stdin=subprocess.PIPE) |
| 49 |
output, error = p.communicate(buf.encode(encoding)) |
| 50 |
if error: |
| 51 |
print(error) |
| 52 |
self.view.replace( |
| 53 |
edit, sublime.Region(0, self.view.size()), |
| 54 |
output.decode(encoding)) |
| 55 |
self.view.sel().clear() |
| 56 |
for region in regions: |
| 57 |
self.view.sel().add(region) |
| 58 |
|
| 59 |
sublime.set_timeout(lambda: self.view.set_viewport_position( |
| 60 |
old_viewport_position, False), 10) |