Home | History | Annotate | Download | only in clang-format
      1 # This file is a minimal clang-format sublime-integration. To install:
      2 # - Change 'binary' if clang-format is not on the path (see below).
      3 # - Put this file into your sublime Packages directory, e.g. on Linux:
      4 #     ~/.config/sublime-text-2/Packages/User/clang-format-sublime.py
      5 # - Add a key binding:
      6 #     { "keys": ["ctrl+shift+c"], "command": "clang_format" },
      7 #
      8 # With this integration you can press the bound key and clang-format will
      9 # format the current lines and selections for all cursor positions. The lines
     10 # or regions are extended to the next bigger syntactic entities.
     11 #
     12 # It operates on the current, potentially unsaved buffer and does not create
     13 # or save any files. To revert a formatting, just undo.
     14 
     15 import sublime
     16 import sublime_plugin
     17 import subprocess
     18 
     19 # Change this to the full path if clang-format is not on the path.
     20 binary = 'clang-format'
     21 
     22 # Change this to format according to other formatting styles
     23 # (see clang-format -help).
     24 style = 'LLVM'
     25 
     26 class ClangFormatCommand(sublime_plugin.TextCommand):
     27   def run(self, edit):
     28     encoding = self.view.encoding()
     29     if encoding == 'Undefined':
     30       encoding = 'utf-8'
     31     regions = []
     32     command = [binary, '-style', style]
     33     for region in self.view.sel():
     34       regions.append(region)
     35       region_offset = min(region.a, region.b)
     36       region_length = abs(region.b - region.a)
     37       command.extend(['-offset', str(region_offset),
     38                       '-length', str(region_length)])
     39     old_viewport_position = self.view.viewport_position()
     40     buf = self.view.substr(sublime.Region(0, self.view.size()))
     41     p = subprocess.Popen(command, stdout=subprocess.PIPE,
     42                          stderr=subprocess.PIPE, stdin=subprocess.PIPE)
     43     output, error = p.communicate(buf.encode(encoding))
     44     if not error:
     45       self.view.replace(
     46           edit, sublime.Region(0, self.view.size()),
     47           output.decode(encoding))
     48       self.view.sel().clear()
     49       for region in regions:
     50         self.view.sel().add(region)
     51       # FIXME: Without the 10ms delay, the viewport sometimes jumps.
     52       sublime.set_timeout(lambda: self.view.set_viewport_position(
     53         old_viewport_position, False), 10)
     54     else:
     55       print error
     56