sync.lua 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. -- Notes on incremental sync:
  2. -- Per the protocol, the text range should be:
  3. --
  4. -- A position inside a document (see Position definition below) is expressed as
  5. -- a zero-based line and character offset. The offsets are based on a UTF-16
  6. -- string representation. So a string of the form a𐐀b the character offset
  7. -- of the character a is 0, the character offset of 𐐀 is 1 and the character
  8. -- offset of b is 3 since 𐐀 is represented using two code units in UTF-16.
  9. --
  10. -- To ensure that both client and server split the string into the same line
  11. -- representation the protocol specifies the following end-of-line sequences: ‘\n’, ‘\r\n’ and ‘\r’.
  12. --
  13. -- Positions are line end character agnostic. So you can not specify a position that
  14. -- denotes \r|\n or \n| where | represents the character offset. This means *no* defining
  15. -- a range than ends on the same line after a terminating character
  16. --
  17. -- Generic warnings about byte level changes in neovim. Many apparently "single"
  18. -- operations in on_lines callbacks are actually multiple operations.
  19. --
  20. -- Join operation (2 operations):
  21. -- * extends line 1 with the contents of line 2
  22. -- * deletes line 2
  23. --
  24. -- test 1 test 1 test 2 test 1 test 2
  25. -- test 2 -> test 2 -> test 3
  26. -- test 3 test 3
  27. --
  28. -- Deleting (and undoing) two middle lines (1 operation):
  29. --
  30. -- test 1 test 1
  31. -- test 2 -> test 4
  32. -- test 3
  33. -- test 4
  34. --
  35. -- Deleting partial lines (5 operations) deleting between asterisks below:
  36. --
  37. -- test *1 test * test * test * test *4 test *4*
  38. -- test 2 -> test 2 -> test *4 -> *4 -> *4 ->
  39. -- test 3 test 3
  40. -- test *4 test 4
  41. local M = {}
  42. -- local string.byte, unclear if this is necessary for JIT compilation
  43. local str_byte = string.byte
  44. local min = math.min
  45. local str_utfindex = vim.str_utfindex
  46. local str_utf_start = vim.str_utf_start
  47. local str_utf_end = vim.str_utf_end
  48. -- Given a line, byte idx, alignment, and position_encoding convert to the aligned
  49. -- utf-8 index and either the utf-16, or utf-32 index.
  50. ---@param line string the line to index into
  51. ---@param byte integer the byte idx
  52. ---@param position_encoding string utf-8|utf-16|utf-32|nil (default: utf-8)
  53. ---@return integer byte_idx of first change position
  54. ---@return integer char_idx of first change position
  55. local function align_end_position(line, byte, position_encoding)
  56. local char --- @type integer
  57. -- If on the first byte, or an empty string: the trivial case
  58. if byte == 1 or #line == 0 then
  59. char = byte
  60. -- Called in the case of extending an empty line "" -> "a"
  61. elseif byte == #line + 1 then
  62. char = str_utfindex(line, position_encoding) + 1
  63. else
  64. -- Modifying line, find the nearest utf codepoint
  65. local offset = str_utf_start(line, byte)
  66. -- If the byte does not fall on the start of the character, then
  67. -- align to the start of the next character.
  68. if offset < 0 then
  69. byte = byte + str_utf_end(line, byte) + 1
  70. end
  71. if byte <= #line then
  72. --- Convert to 0 based for input, and from 0 based for output
  73. char = str_utfindex(line, position_encoding, byte - 1) + 1
  74. else
  75. char = str_utfindex(line, position_encoding) + 1
  76. end
  77. -- Extending line, find the nearest utf codepoint for the last valid character
  78. end
  79. return byte, char
  80. end
  81. ---@class vim.lsp.sync.Range
  82. ---@field line_idx integer
  83. ---@field byte_idx integer
  84. ---@field char_idx integer
  85. --- Finds the first line, byte, and char index of the difference between the previous and current lines buffer normalized to the previous codepoint.
  86. ---@param prev_lines string[] list of lines from previous buffer
  87. ---@param curr_lines string[] list of lines from current buffer
  88. ---@param firstline integer firstline from on_lines, adjusted to 1-index
  89. ---@param lastline integer lastline from on_lines, adjusted to 1-index
  90. ---@param new_lastline integer new_lastline from on_lines, adjusted to 1-index
  91. ---@param position_encoding string utf-8|utf-16|utf-32|nil (fallback to utf-8)
  92. ---@return vim.lsp.sync.Range result table include line_idx, byte_idx, and char_idx of first change position
  93. local function compute_start_range(
  94. prev_lines,
  95. curr_lines,
  96. firstline,
  97. lastline,
  98. new_lastline,
  99. position_encoding
  100. )
  101. local char_idx --- @type integer?
  102. local byte_idx --- @type integer?
  103. -- If firstline == lastline, no existing text is changed. All edit operations
  104. -- occur on a new line pointed to by lastline. This occurs during insertion of
  105. -- new lines(O), the new newline is inserted at the line indicated by
  106. -- new_lastline.
  107. if firstline == lastline then
  108. local line_idx --- @type integer
  109. local line = prev_lines[firstline - 1]
  110. if line then
  111. line_idx = firstline - 1
  112. byte_idx = #line + 1
  113. char_idx = str_utfindex(line, position_encoding) + 1
  114. else
  115. line_idx = firstline
  116. byte_idx = 1
  117. char_idx = 1
  118. end
  119. return { line_idx = line_idx, byte_idx = byte_idx, char_idx = char_idx }
  120. end
  121. -- If firstline == new_lastline, the first change occurred on a line that was deleted.
  122. -- In this case, the first byte change is also at the first byte of firstline
  123. if firstline == new_lastline then
  124. return { line_idx = firstline, byte_idx = 1, char_idx = 1 }
  125. end
  126. local prev_line = prev_lines[firstline]
  127. local curr_line = curr_lines[firstline]
  128. -- Iterate across previous and current line containing first change
  129. -- to find the first different byte.
  130. -- Note: *about -> a*about will register the second a as the first
  131. -- difference, regardless of edit since we do not receive the first
  132. -- column of the edit from on_lines.
  133. local start_byte_idx = 1
  134. for idx = 1, #prev_line + 1 do
  135. start_byte_idx = idx
  136. if str_byte(prev_line, idx) ~= str_byte(curr_line, idx) then
  137. break
  138. end
  139. end
  140. -- Convert byte to codepoint if applicable
  141. if start_byte_idx == 1 or (#prev_line == 0 and start_byte_idx == 1) then
  142. byte_idx = start_byte_idx
  143. char_idx = 1
  144. elseif start_byte_idx == #prev_line + 1 then
  145. byte_idx = start_byte_idx
  146. char_idx = str_utfindex(prev_line, position_encoding) + 1
  147. else
  148. byte_idx = start_byte_idx + str_utf_start(prev_line, start_byte_idx)
  149. --- Convert to 0 based for input, and from 0 based for output
  150. char_idx = vim.str_utfindex(prev_line, position_encoding, byte_idx - 1) + 1
  151. end
  152. -- Return the start difference (shared for new and prev lines)
  153. return { line_idx = firstline, byte_idx = byte_idx, char_idx = char_idx }
  154. end
  155. --- Finds the last line and byte index of the differences between prev and current buffer.
  156. --- Normalized to the next codepoint.
  157. --- prev_end_range is the text range sent to the server representing the changed region.
  158. --- curr_end_range is the text that should be collected and sent to the server.
  159. ---
  160. ---@param prev_lines string[] list of lines
  161. ---@param curr_lines string[] list of lines
  162. ---@param start_range vim.lsp.sync.Range
  163. ---@param firstline integer
  164. ---@param lastline integer
  165. ---@param new_lastline integer
  166. ---@param position_encoding string
  167. ---@return vim.lsp.sync.Range prev_end_range
  168. ---@return vim.lsp.sync.Range curr_end_range
  169. local function compute_end_range(
  170. prev_lines,
  171. curr_lines,
  172. start_range,
  173. firstline,
  174. lastline,
  175. new_lastline,
  176. position_encoding
  177. )
  178. -- A special case for the following `firstline == new_lastline` case where lines are deleted.
  179. -- Even if the buffer has become empty, nvim behaves as if it has an empty line with eol.
  180. if #curr_lines == 1 and curr_lines[1] == '' then
  181. local prev_line = prev_lines[lastline - 1]
  182. return {
  183. line_idx = lastline - 1,
  184. byte_idx = #prev_line + 1,
  185. char_idx = str_utfindex(prev_line, position_encoding) + 1,
  186. }, { line_idx = 1, byte_idx = 1, char_idx = 1 }
  187. end
  188. -- If firstline == new_lastline, the first change occurred on a line that was deleted.
  189. -- In this case, the last_byte...
  190. if firstline == new_lastline then
  191. return { line_idx = (lastline - new_lastline + firstline), byte_idx = 1, char_idx = 1 }, {
  192. line_idx = firstline,
  193. byte_idx = 1,
  194. char_idx = 1,
  195. }
  196. end
  197. if firstline == lastline then
  198. return { line_idx = firstline, byte_idx = 1, char_idx = 1 }, {
  199. line_idx = new_lastline - lastline + firstline,
  200. byte_idx = 1,
  201. char_idx = 1,
  202. }
  203. end
  204. -- Compare on last line, at minimum will be the start range
  205. local start_line_idx = start_range.line_idx
  206. -- lastline and new_lastline were last lines that were *not* replaced, compare previous lines
  207. local prev_line_idx = lastline - 1
  208. local curr_line_idx = new_lastline - 1
  209. local prev_line = prev_lines[lastline - 1]
  210. local curr_line = curr_lines[new_lastline - 1]
  211. local prev_line_length = #prev_line
  212. local curr_line_length = #curr_line
  213. local byte_offset = 0
  214. -- Editing the same line
  215. -- If the byte offset is zero, that means there is a difference on the last byte (not newline)
  216. if prev_line_idx == curr_line_idx then
  217. local max_length --- @type integer
  218. if start_line_idx == prev_line_idx then
  219. -- Search until beginning of difference
  220. max_length = min(
  221. prev_line_length - start_range.byte_idx,
  222. curr_line_length - start_range.byte_idx
  223. ) + 1
  224. else
  225. max_length = min(prev_line_length, curr_line_length) + 1
  226. end
  227. for idx = 0, max_length do
  228. byte_offset = idx
  229. if
  230. str_byte(prev_line, prev_line_length - byte_offset)
  231. ~= str_byte(curr_line, curr_line_length - byte_offset)
  232. then
  233. break
  234. end
  235. end
  236. end
  237. -- Iterate from end to beginning of shortest line
  238. local prev_end_byte_idx = prev_line_length - byte_offset + 1
  239. -- Handle case where lines match
  240. if prev_end_byte_idx == 0 then
  241. prev_end_byte_idx = 1
  242. end
  243. local prev_byte_idx, prev_char_idx =
  244. align_end_position(prev_line, prev_end_byte_idx, position_encoding)
  245. local prev_end_range =
  246. { line_idx = prev_line_idx, byte_idx = prev_byte_idx, char_idx = prev_char_idx }
  247. local curr_end_range ---@type vim.lsp.sync.Range
  248. -- Deletion event, new_range cannot be before start
  249. if curr_line_idx < start_line_idx then
  250. curr_end_range = { line_idx = start_line_idx, byte_idx = 1, char_idx = 1 }
  251. else
  252. local curr_end_byte_idx = curr_line_length - byte_offset + 1
  253. -- Handle case where lines match
  254. if curr_end_byte_idx == 0 then
  255. curr_end_byte_idx = 1
  256. end
  257. local curr_byte_idx, curr_char_idx =
  258. align_end_position(curr_line, curr_end_byte_idx, position_encoding)
  259. curr_end_range =
  260. { line_idx = curr_line_idx, byte_idx = curr_byte_idx, char_idx = curr_char_idx }
  261. end
  262. return prev_end_range, curr_end_range
  263. end
  264. --- Get the text of the range defined by start and end line/column
  265. ---@param lines table list of lines
  266. ---@param start_range table table returned by first_difference
  267. ---@param end_range table new_end_range returned by last_difference
  268. ---@return string text extracted from defined region
  269. local function extract_text(lines, start_range, end_range, line_ending)
  270. if not lines[start_range.line_idx] then
  271. return ''
  272. end
  273. -- Trivial case: start and end range are the same line, directly grab changed text
  274. if start_range.line_idx == end_range.line_idx then
  275. -- string.sub is inclusive, end_range is not
  276. return string.sub(lines[start_range.line_idx], start_range.byte_idx, end_range.byte_idx - 1)
  277. else
  278. -- Handle deletion case
  279. -- Collect the changed portion of the first changed line
  280. local result = { string.sub(lines[start_range.line_idx], start_range.byte_idx) }
  281. -- Collect the full line for intermediate lines
  282. for idx = start_range.line_idx + 1, end_range.line_idx - 1 do
  283. table.insert(result, lines[idx])
  284. end
  285. if lines[end_range.line_idx] then
  286. -- Collect the changed portion of the last changed line.
  287. table.insert(result, string.sub(lines[end_range.line_idx], 1, end_range.byte_idx - 1))
  288. else
  289. table.insert(result, '')
  290. end
  291. -- Add line ending between all lines
  292. return table.concat(result, line_ending)
  293. end
  294. end
  295. -- rangelength depends on the position encoding
  296. -- bytes for utf-8 (clangd with extension)
  297. -- codepoints for utf-16
  298. -- codeunits for utf-32
  299. -- Line endings count here as 2 chars for \r\n (dos), 1 char for \n (unix), and 1 char for \r (mac)
  300. -- These correspond to Windows, Linux/macOS (OSX and newer), and macOS (version 9 and prior)
  301. ---@param lines string[]
  302. ---@param start_range vim.lsp.sync.Range
  303. ---@param end_range vim.lsp.sync.Range
  304. ---@param position_encoding string
  305. ---@param line_ending string
  306. ---@return integer
  307. local function compute_range_length(lines, start_range, end_range, position_encoding, line_ending)
  308. local line_ending_length = #line_ending
  309. -- Single line case
  310. if start_range.line_idx == end_range.line_idx then
  311. return end_range.char_idx - start_range.char_idx
  312. end
  313. local start_line = lines[start_range.line_idx]
  314. local range_length --- @type integer
  315. if start_line and #start_line > 0 then
  316. range_length = str_utfindex(start_line, position_encoding)
  317. - start_range.char_idx
  318. + 1
  319. + line_ending_length
  320. else
  321. -- Length of newline character
  322. range_length = line_ending_length
  323. end
  324. -- The first and last range of the line idx may be partial lines
  325. for idx = start_range.line_idx + 1, end_range.line_idx - 1 do
  326. -- Length full line plus newline character
  327. if #lines[idx] > 0 then
  328. range_length = range_length + str_utfindex(lines[idx], position_encoding) + #line_ending
  329. else
  330. range_length = range_length + line_ending_length
  331. end
  332. end
  333. local end_line = lines[end_range.line_idx]
  334. if end_line and #end_line > 0 then
  335. range_length = range_length + end_range.char_idx - 1
  336. end
  337. return range_length
  338. end
  339. --- Returns the range table for the difference between prev and curr lines
  340. ---@param prev_lines table list of lines
  341. ---@param curr_lines table list of lines
  342. ---@param firstline integer line to begin search for first difference
  343. ---@param lastline integer line to begin search in old_lines for last difference
  344. ---@param new_lastline integer line to begin search in new_lines for last difference
  345. ---@param position_encoding string encoding requested by language server
  346. ---@param line_ending string
  347. ---@return lsp.TextDocumentContentChangeEvent : see https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent
  348. function M.compute_diff(
  349. prev_lines,
  350. curr_lines,
  351. firstline,
  352. lastline,
  353. new_lastline,
  354. position_encoding,
  355. line_ending
  356. )
  357. -- Find the start of changes between the previous and current buffer. Common between both.
  358. -- Sent to the server as the start of the changed range.
  359. -- Used to grab the changed text from the latest buffer.
  360. local start_range = compute_start_range(
  361. prev_lines,
  362. curr_lines,
  363. firstline + 1,
  364. lastline + 1,
  365. new_lastline + 1,
  366. position_encoding
  367. )
  368. -- Find the last position changed in the previous and current buffer.
  369. -- prev_end_range is sent to the server as as the end of the changed range.
  370. -- curr_end_range is used to grab the changed text from the latest buffer.
  371. local prev_end_range, curr_end_range = compute_end_range(
  372. prev_lines,
  373. curr_lines,
  374. start_range,
  375. firstline + 1,
  376. lastline + 1,
  377. new_lastline + 1,
  378. position_encoding
  379. )
  380. -- Grab the changed text of from start_range to curr_end_range in the current buffer.
  381. -- The text range is "" if entire range is deleted.
  382. local text = extract_text(curr_lines, start_range, curr_end_range, line_ending)
  383. -- Compute the range of the replaced text. Deprecated but still required for certain language servers
  384. local range_length =
  385. compute_range_length(prev_lines, start_range, prev_end_range, position_encoding, line_ending)
  386. -- convert to 0 based indexing
  387. local result = {
  388. range = {
  389. ['start'] = { line = start_range.line_idx - 1, character = start_range.char_idx - 1 },
  390. ['end'] = { line = prev_end_range.line_idx - 1, character = prev_end_range.char_idx - 1 },
  391. },
  392. text = text,
  393. rangeLength = range_length,
  394. }
  395. return result
  396. end
  397. return M