1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 # Based on clang-format.py.
7 # This file is a minimal gn format vim-integration. To install:
8 # - Change 'binary' if gn is not on the path (see below).
9 # - Add to your .vimrc:
11 # map <F1> :pyf <path-to-this-file>/gn-format.py<CR>
13 # gn format currently formats only a complete file so visual ranges, etc. won't
14 # be used. It operates on the current, potentially unsaved buffer and does not
15 # create or save any files. To revert a formatting, just undo.
22 # Change this to the full path if gn is not on the path.
26 # Get the current text.
27 buf
= vim
.current
.buffer
30 # Avoid flashing an ugly cmd prompt on Windows when invoking gn.
32 if sys
.platform
.startswith('win32'):
33 startupinfo
= subprocess
.STARTUPINFO()
34 startupinfo
.dwFlags |
= subprocess
.STARTF_USESHOWWINDOW
35 startupinfo
.wShowWindow
= subprocess
.SW_HIDE
38 p
= subprocess
.Popen([binary
, 'format', '--stdin'],
39 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
,
40 stdin
=subprocess
.PIPE
, startupinfo
=startupinfo
,
41 universal_newlines
=True)
42 stdout
, stderr
= p
.communicate(input=text
)
44 print 'Formatting failed, please report to gn-dev@chromium.org.'
47 # Otherwise, replace current buffer.
48 lines
= stdout
.split('\n')
49 # Last line should have trailing \n, but we don't want to insert a blank
50 # line at the end of the buffer, so remove that.
53 sequence
= difflib
.SequenceMatcher(None, vim
.current
.buffer, lines
)
54 for op
in reversed(sequence
.get_opcodes()):
55 if op
[0] is not 'equal':
56 vim
.current
.buffer[op
[1]:op
[2]] = lines
[op
[3]:op
[4]]