clang-format-sublime.py 2.4 KB

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