clang-format-sublime.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. import sublime
  15. import sublime_plugin
  16. import subprocess
  17. # Change this to the full path if clang-format is not on the path.
  18. binary = 'clang-format'
  19. # Change this to format according to other formatting styles. See the output of
  20. # 'clang-format --help' for a list of supported styles. The default looks for
  21. # a '.clang-format' file to indicate the style that should be used.
  22. style = 'file'
  23. class ClangFormatCommand(sublime_plugin.TextCommand):
  24. def run(self, edit):
  25. encoding = self.view.encoding()
  26. if encoding == 'Undefined':
  27. encoding = 'utf-8'
  28. regions = []
  29. command = [binary, '-style', style]
  30. for region in self.view.sel():
  31. regions.append(region)
  32. region_offset = min(region.a, region.b)
  33. region_length = abs(region.b - region.a)
  34. command.extend(['-offset', str(region_offset),
  35. '-length', str(region_length)])
  36. old_viewport_position = self.view.viewport_position()
  37. buf = self.view.substr(sublime.Region(0, self.view.size()))
  38. p = subprocess.Popen(command, stdout=subprocess.PIPE,
  39. stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  40. output, error = p.communicate(buf.encode(encoding))
  41. if not error:
  42. self.view.replace(
  43. edit, sublime.Region(0, self.view.size()),
  44. output.decode(encoding))
  45. self.view.sel().clear()
  46. for region in regions:
  47. self.view.sel().add(region)
  48. # FIXME: Without the 10ms delay, the viewport sometimes jumps.
  49. sublime.set_timeout(lambda: self.view.set_viewport_position(
  50. old_viewport_position, False), 10)
  51. else:
  52. print error