@@ -55,6 +55,36 @@ function! s:ClangFormatHasAtLeastVersion(minimum_version) abort
5555endfunction
5656
5757
58+ " Inputs are 1-based (row, col) coordinates into lines.
59+ " Returns the corresponding zero-based offset into lines->join("\n")
60+ function ! s: PositionToOffset (row, col , lines ) abort
61+ let l: offset = a: col - 1
62+ if a: row > 1
63+ for l: line in a: lines [0 : a: row - 2 ]
64+ let l: offset += len (l: line ) + 1
65+ endfor
66+ endif
67+ return l: offset
68+ endfunction
69+
70+
71+ " Input is zero-based offset into lines->join("\n")
72+ " Returns the 1-based [row, col] coordinates into lines.
73+ function ! s: OffsetToPosition (offset, lines ) abort
74+ let l: lines_consumed = 0
75+ let l: chars_left = a: offset
76+ for l: line in a: lines
77+ let l: chars_after_next = l: chars_left - len (l: line ) - 1
78+ if l: chars_after_next < 0
79+ break
80+ endif
81+ let l: chars_left = l: chars_after_next
82+ let l: lines_consumed += 1
83+ endfor
84+ return [l: lines_consumed + 1 , l: chars_left + 1 ]
85+ endfunction
86+
87+
5888" "
5989" @private
6090" Invalidates the cached clang-format version.
@@ -127,10 +157,7 @@ function! codefmt#clangformat#GetFormatter() abort
127157 let l: supports_cursor = s: ClangFormatHasAtLeastVersion ([3 , 4 ])
128158 if l: supports_cursor
129159 " Avoid line2byte: https://github.com/vim/vim/issues/5930
130- let l: cursor_pos = col (' .' ) - 1
131- for l: i in range (1 , line (' .' ) - 1 )
132- let l: cursor_pos += len (l: lines [l: i - 1 ]) + 1
133- endfor
160+ let l: cursor_pos = s: PositionToOffset (line (' .' ), col (' .' ), l: lines )
134161 let l: cmd += [' -cursor' , string (l: cursor_pos )]
135162 endif
136163
@@ -140,23 +167,14 @@ function! codefmt#clangformat#GetFormatter() abort
140167
141168 if l: supports_cursor
142169 " With -cursor, the first line is a JSON object.
143- let l: header = l: formatted [0 ]
144- let l: formatted = l: formatted [1 :]
170+ let l: header = remove (l: formatted , 0 )
145171 call maktaba#buffer#Overwrite (1 , line (' $' ), l: formatted )
146172 try
147173 let l: header_json = maktaba#json#Parse (l: header )
148174 let l: offset = maktaba#ensure#IsNumber (l: header_json .Cursor )
149175 " Compute line/col, avoid goto: https://github.com/vim/vim/issues/5930
150- let l: new_line = 0
151- for l: line in l: formatted
152- let l: offset_after_next = l: offset - len (l: line ) - 1
153- if l: offset_after_next < 0
154- break
155- endif
156- let l: offset = l: offset_after_next
157- let l: new_line += 1
158- endfor
159- call cursor (l: new_line + 1 , l: offset + 1 )
176+ let [l: new_line , l: new_col ] = s: OffsetToPosition (l: offset , l: formatted )
177+ call cursor (l: new_line , l: new_col )
160178 catch
161179 call maktaba#error#Warn (' Unable to parse clang-format cursor pos: %s' ,
162180 \ v: exception )
0 commit comments