blob: 0c772f91f6f229979c80815ada171fb6eaa76a27 [file] [log] [blame]
djasper7f663602013-03-20 09:53:23 +00001# This file is a minimal clang-format vim-integration. To install:
2# - Change 'binary' if clang-format is not on the path (see below).
3# - Add to your .vimrc:
4#
compnerd9216b272014-10-27 17:13:33 +00005# map <C-I> :pyf <path-to-this-file>/clang-format.py<cr>
compnerd3ddc3412014-11-02 21:27:52 +00006# imap <C-I> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
djasper7f663602013-03-20 09:53:23 +00007#
8# The first line enables clang-format for NORMAL and VISUAL mode, the second
9# line adds support for INSERT mode. Change "C-I" to another binding if you
10# need clang-format on a different key (C-I stands for Ctrl+i).
11#
12# With this integration you can press the bound key and clang-format will
13# format the current line in NORMAL and INSERT mode or the selected region in
14# VISUAL mode. The line or region is extended to the next bigger syntactic
15# entity.
16#
djasper9de4e3f2015-07-11 06:46:26 +000017# You can also pass in the variable "l:lines" to choose the range for
18# formatting. This variable can either contain "<start line>:<end line>" or
19# "all" to format the full file. So, to format the full file, write a function
20# like:
21# :function FormatFile()
22# : let l:lines="all"
23# : pyf <path-to-this-file>/clang-format.py
24# :endfunction
25#
djasper7f663602013-03-20 09:53:23 +000026# It operates on the current, potentially unsaved buffer and does not create
27# or save any files. To revert a formatting, just undo.
serge_sans_paille05613342018-12-18 16:07:37 +000028from __future__ import absolute_import, division, print_function
djasper7f663602013-03-20 09:53:23 +000029
djasperb7e02b12013-07-21 10:45:33 +000030import difflib
djasperd0252b72013-05-21 12:21:39 +000031import json
vedantkf8c29ee2016-12-10 00:54:13 +000032import platform
djasper7f663602013-03-20 09:53:23 +000033import subprocess
rnk8f191962013-06-10 14:16:26 +000034import sys
djasperd0252b72013-05-21 12:21:39 +000035import vim
djasper7f663602013-03-20 09:53:23 +000036
compnerde19f7442014-11-02 21:27:59 +000037# set g:clang_format_path to the path to clang-format if it is not on the path
djasper7f663602013-03-20 09:53:23 +000038# Change this to the full path if clang-format is not on the path.
39binary = 'clang-format'
djasper7480ff12014-11-04 10:40:26 +000040if vim.eval('exists("g:clang_format_path")') == "1":
compnerde19f7442014-11-02 21:27:59 +000041 binary = vim.eval('g:clang_format_path')
djasper7f663602013-03-20 09:53:23 +000042
chandlerce6992fd2013-09-02 07:42:02 +000043# Change this to format according to other formatting styles. See the output of
44# 'clang-format --help' for a list of supported styles. The default looks for
hans79a882f2013-09-10 15:41:12 +000045# a '.clang-format' or '_clang-format' file to indicate the style that should be
46# used.
sammccall2b978b62019-05-17 07:22:55 +000047style = None
djasper701b33d2015-04-17 07:59:19 +000048fallback_style = None
djasper0f3ae422015-04-16 08:26:37 +000049if vim.eval('exists("g:clang_format_fallback_style")') == "1":
50 fallback_style = vim.eval('g:clang_format_fallback_style')
djasper05e73312013-04-09 15:23:04 +000051
vedantkf8c29ee2016-12-10 00:54:13 +000052def get_buffer(encoding):
53 if platform.python_version_tuple()[0] == '3':
54 return vim.current.buffer
55 return [ line.decode(encoding) for line in vim.current.buffer ]
56
ace2001acba28cea2014-03-10 22:12:14 +000057def main():
58 # Get the current text.
ldrumm73289d72016-08-31 13:36:36 +000059 encoding = vim.eval("&encoding")
vedantkf8c29ee2016-12-10 00:54:13 +000060 buf = get_buffer(encoding)
alexfh5a365782016-10-27 13:46:49 +000061 text = '\n'.join(buf)
djasper7f663602013-03-20 09:53:23 +000062
ace2001acba28cea2014-03-10 22:12:14 +000063 # Determine range to format.
djasper9de4e3f2015-07-11 06:46:26 +000064 if vim.eval('exists("l:lines")') == '1':
krasimir4f861202017-08-22 14:28:01 +000065 lines = ['-lines', vim.eval('l:lines')]
djasper7b504522017-06-19 07:30:04 +000066 elif vim.eval('exists("l:formatdiff")') == '1':
67 with open(vim.current.buffer.name, 'r') as f:
68 ondisk = f.read().splitlines();
69 sequence = difflib.SequenceMatcher(None, ondisk, vim.current.buffer)
70 lines = []
71 for op in reversed(sequence.get_opcodes()):
72 if op[0] not in ['equal', 'delete']:
73 lines += ['-lines', '%s:%s' % (op[3] + 1, op[4])]
74 if lines == []:
75 return
djasper9de4e3f2015-07-11 06:46:26 +000076 else:
djasper7b504522017-06-19 07:30:04 +000077 lines = ['-lines', '%s:%s' % (vim.current.range.start + 1,
78 vim.current.range.end + 1)]
djasper7f663602013-03-20 09:53:23 +000079
djasper4d1cfae2014-05-22 11:37:05 +000080 # Determine the cursor position.
81 cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
82 if cursor < 0:
ldrumm73289d72016-08-31 13:36:36 +000083 print('Couldn\'t determine cursor position. Is your file empty?')
djasper4d1cfae2014-05-22 11:37:05 +000084 return
85
ace2001acba28cea2014-03-10 22:12:14 +000086 # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
87 startupinfo = None
88 if sys.platform.startswith('win32'):
89 startupinfo = subprocess.STARTUPINFO()
90 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
91 startupinfo.wShowWindow = subprocess.SW_HIDE
rnk8f191962013-06-10 14:16:26 +000092
ace2001acba28cea2014-03-10 22:12:14 +000093 # Call formatter.
sammccall2b978b62019-05-17 07:22:55 +000094 command = [binary, '-cursor', str(cursor)]
krasimirb9626372017-09-05 13:58:53 +000095 if lines != ['-lines', 'all']:
djasper7b504522017-06-19 07:30:04 +000096 command += lines
sammccall2b978b62019-05-17 07:22:55 +000097 if style:
98 command.extend(['-style', style])
djasper0f3ae422015-04-16 08:26:37 +000099 if fallback_style:
100 command.extend(['-fallback-style', fallback_style])
ace2001acba28cea2014-03-10 22:12:14 +0000101 if vim.current.buffer.name:
102 command.extend(['-assume-filename', vim.current.buffer.name])
103 p = subprocess.Popen(command,
104 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
105 stdin=subprocess.PIPE, startupinfo=startupinfo)
ldrumm73289d72016-08-31 13:36:36 +0000106 stdout, stderr = p.communicate(input=text.encode(encoding))
djasper7f663602013-03-20 09:53:23 +0000107
ace2001acba28cea2014-03-10 22:12:14 +0000108 # If successful, replace buffer contents.
109 if stderr:
ldrumm73289d72016-08-31 13:36:36 +0000110 print(stderr)
djasper7f663602013-03-20 09:53:23 +0000111
ace2001acba28cea2014-03-10 22:12:14 +0000112 if not stdout:
ldrumm73289d72016-08-31 13:36:36 +0000113 print(
114 'No output from clang-format (crashed?).\n'
115 'Please report to bugs.llvm.org.'
116 )
ace2001acba28cea2014-03-10 22:12:14 +0000117 else:
ldrumm73289d72016-08-31 13:36:36 +0000118 lines = stdout.decode(encoding).split('\n')
ace2001acba28cea2014-03-10 22:12:14 +0000119 output = json.loads(lines[0])
120 lines = lines[1:]
alexfh5a365782016-10-27 13:46:49 +0000121 sequence = difflib.SequenceMatcher(None, buf, lines)
ace2001acba28cea2014-03-10 22:12:14 +0000122 for op in reversed(sequence.get_opcodes()):
123 if op[0] is not 'equal':
124 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
chandlerc02debe82015-06-04 21:23:07 +0000125 if output.get('IncompleteFormat'):
ldrumm73289d72016-08-31 13:36:36 +0000126 print('clang-format: incomplete (syntax errors)')
ace2001acba28cea2014-03-10 22:12:14 +0000127 vim.command('goto %d' % (output['Cursor'] + 1))
128
129main()