xref: /aosp_15_r20/external/clang/tools/clang-format/clang-format.py (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li# This file is a minimal clang-format vim-integration. To install:
2*67e74705SXin Li# - Change 'binary' if clang-format is not on the path (see below).
3*67e74705SXin Li# - Add to your .vimrc:
4*67e74705SXin Li#
5*67e74705SXin Li#   map <C-I> :pyf <path-to-this-file>/clang-format.py<cr>
6*67e74705SXin Li#   imap <C-I> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
7*67e74705SXin Li#
8*67e74705SXin Li# The first line enables clang-format for NORMAL and VISUAL mode, the second
9*67e74705SXin Li# line adds support for INSERT mode. Change "C-I" to another binding if you
10*67e74705SXin Li# need clang-format on a different key (C-I stands for Ctrl+i).
11*67e74705SXin Li#
12*67e74705SXin Li# With this integration you can press the bound key and clang-format will
13*67e74705SXin Li# format the current line in NORMAL and INSERT mode or the selected region in
14*67e74705SXin Li# VISUAL mode. The line or region is extended to the next bigger syntactic
15*67e74705SXin Li# entity.
16*67e74705SXin Li#
17*67e74705SXin Li# You can also pass in the variable "l:lines" to choose the range for
18*67e74705SXin Li# formatting. This variable can either contain "<start line>:<end line>" or
19*67e74705SXin Li# "all" to format the full file. So, to format the full file, write a function
20*67e74705SXin Li# like:
21*67e74705SXin Li# :function FormatFile()
22*67e74705SXin Li# :  let l:lines="all"
23*67e74705SXin Li# :  pyf <path-to-this-file>/clang-format.py
24*67e74705SXin Li# :endfunction
25*67e74705SXin Li#
26*67e74705SXin Li# It operates on the current, potentially unsaved buffer and does not create
27*67e74705SXin Li# or save any files. To revert a formatting, just undo.
28*67e74705SXin Li
29*67e74705SXin Liimport difflib
30*67e74705SXin Liimport json
31*67e74705SXin Liimport subprocess
32*67e74705SXin Liimport sys
33*67e74705SXin Liimport vim
34*67e74705SXin Li
35*67e74705SXin Li# set g:clang_format_path to the path to clang-format if it is not on the path
36*67e74705SXin Li# Change this to the full path if clang-format is not on the path.
37*67e74705SXin Libinary = 'clang-format'
38*67e74705SXin Liif vim.eval('exists("g:clang_format_path")') == "1":
39*67e74705SXin Li  binary = vim.eval('g:clang_format_path')
40*67e74705SXin Li
41*67e74705SXin Li# Change this to format according to other formatting styles. See the output of
42*67e74705SXin Li# 'clang-format --help' for a list of supported styles. The default looks for
43*67e74705SXin Li# a '.clang-format' or '_clang-format' file to indicate the style that should be
44*67e74705SXin Li# used.
45*67e74705SXin Listyle = 'file'
46*67e74705SXin Lifallback_style = None
47*67e74705SXin Liif vim.eval('exists("g:clang_format_fallback_style")') == "1":
48*67e74705SXin Li  fallback_style = vim.eval('g:clang_format_fallback_style')
49*67e74705SXin Li
50*67e74705SXin Lidef main():
51*67e74705SXin Li  # Get the current text.
52*67e74705SXin Li  buf = vim.current.buffer
53*67e74705SXin Li  text = '\n'.join(buf)
54*67e74705SXin Li
55*67e74705SXin Li  # Determine range to format.
56*67e74705SXin Li  if vim.eval('exists("l:lines")') == '1':
57*67e74705SXin Li    lines = vim.eval('l:lines')
58*67e74705SXin Li  else:
59*67e74705SXin Li    lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1)
60*67e74705SXin Li
61*67e74705SXin Li  # Determine the cursor position.
62*67e74705SXin Li  cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
63*67e74705SXin Li  if cursor < 0:
64*67e74705SXin Li    print 'Couldn\'t determine cursor position. Is your file empty?'
65*67e74705SXin Li    return
66*67e74705SXin Li
67*67e74705SXin Li  # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
68*67e74705SXin Li  startupinfo = None
69*67e74705SXin Li  if sys.platform.startswith('win32'):
70*67e74705SXin Li    startupinfo = subprocess.STARTUPINFO()
71*67e74705SXin Li    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
72*67e74705SXin Li    startupinfo.wShowWindow = subprocess.SW_HIDE
73*67e74705SXin Li
74*67e74705SXin Li  # Call formatter.
75*67e74705SXin Li  command = [binary, '-style', style, '-cursor', str(cursor)]
76*67e74705SXin Li  if lines != 'all':
77*67e74705SXin Li    command.extend(['-lines', lines])
78*67e74705SXin Li  if fallback_style:
79*67e74705SXin Li    command.extend(['-fallback-style', fallback_style])
80*67e74705SXin Li  if vim.current.buffer.name:
81*67e74705SXin Li    command.extend(['-assume-filename', vim.current.buffer.name])
82*67e74705SXin Li  p = subprocess.Popen(command,
83*67e74705SXin Li                       stdout=subprocess.PIPE, stderr=subprocess.PIPE,
84*67e74705SXin Li                       stdin=subprocess.PIPE, startupinfo=startupinfo)
85*67e74705SXin Li  stdout, stderr = p.communicate(input=text)
86*67e74705SXin Li
87*67e74705SXin Li  # If successful, replace buffer contents.
88*67e74705SXin Li  if stderr:
89*67e74705SXin Li    print stderr
90*67e74705SXin Li
91*67e74705SXin Li  if not stdout:
92*67e74705SXin Li    print ('No output from clang-format (crashed?).\n' +
93*67e74705SXin Li        'Please report to bugs.llvm.org.')
94*67e74705SXin Li  else:
95*67e74705SXin Li    lines = stdout.split('\n')
96*67e74705SXin Li    output = json.loads(lines[0])
97*67e74705SXin Li    lines = lines[1:]
98*67e74705SXin Li    sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
99*67e74705SXin Li    for op in reversed(sequence.get_opcodes()):
100*67e74705SXin Li      if op[0] is not 'equal':
101*67e74705SXin Li        vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
102*67e74705SXin Li    if output.get('IncompleteFormat'):
103*67e74705SXin Li      print 'clang-format: incomplete (syntax errors)'
104*67e74705SXin Li    vim.command('goto %d' % (output['Cursor'] + 1))
105*67e74705SXin Li
106*67e74705SXin Limain()
107