summaryrefslogtreecommitdiffstatshomepage
path: root/runtime/lua/vim/lsp/buf.lua
blob: ad98356ecfbc6acefe94f93c68547a45fa476e1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
--- @brief
--- The `vim.lsp.buf_…` functions perform operations for LSP clients attached to the current buffer.

local api = vim.api
local lsp = vim.lsp
local validate = vim.validate
local util = require('vim.lsp.util')
local npcall = vim.F.npcall

local M = {}

--- @param params? table
--- @return fun(client: vim.lsp.Client): lsp.TextDocumentPositionParams
local function client_positional_params(params)
  local win = api.nvim_get_current_win()
  return function(client)
    local ret = util.make_position_params(win, client.offset_encoding)
    if params then
      ret = vim.tbl_extend('force', ret, params)
    end
    return ret
  end
end

local hover_ns = api.nvim_create_namespace('nvim.lsp.hover_range')
local rename_ns = api.nvim_create_namespace('nvim.lsp.rename_range')

--- Returns false if the LSP response is stale and should be discarded.
--- @param ctx lsp.HandlerContext
--- @return boolean
local function ctx_is_valid(ctx)
  local bufnr = ctx.bufnr
  if
    not bufnr
    or not api.nvim_buf_is_valid(bufnr)
    or api.nvim_get_current_buf() ~= bufnr
    or vim.lsp.util.buf_versions[bufnr] ~= ctx.version
  then
    return false
  end
  local p = ctx.params and ctx.params.position
  if not p then
    return true
  end

  local cur = api.nvim_win_get_cursor(0)
  local c = lsp.get_client_by_id(ctx.client_id)
  local enc = c and c.offset_encoding

  return cur[1] - 1 == p.line and enc and cur[2] == util._get_line_byte_from_position(bufnr, p, enc)
    or false
end

--- @class vim.lsp.buf.hover.Opts : vim.lsp.util.open_floating_preview.Opts
--- @field silent? boolean

--- Displays hover information about the symbol under the cursor in a floating
--- window. The window will be dismissed on cursor move.
--- Calling the function twice will jump into the floating window
--- (thus by default, "KK" will open the hover window and focus it).
--- In the floating window, all commands and mappings are available as usual,
--- except that "q" dismisses the window.
--- You can scroll the contents the same as you would any other buffer.
---
--- Note: to disable hover highlights, add the following to your config:
---
--- ```lua
--- vim.api.nvim_create_autocmd('ColorScheme', {
---   callback = function()
---     vim.api.nvim_set_hl(0, 'LspReferenceTarget', {})
---   end,
--- })
--- ```
--- @param config? vim.lsp.buf.hover.Opts
function M.hover(config)
  validate('config', config, 'table', true)

  config = config or {}
  config.focus_id = 'textDocument/hover'

  lsp.buf_request_all(0, 'textDocument/hover', client_positional_params(), function(results, ctx)
    local bufnr = ctx.bufnr
    if not bufnr or not ctx_is_valid(ctx) then
      return -- Ignore result if context changed. Can happen for slow LS.
    end

    -- Filter errors from results
    local results1 = {} --- @type table<integer,lsp.Hover>
    local nresults = 0
    local empty_response = false

    for client_id, resp in pairs(results) do
      local err, result = resp.err, resp.result
      if err then
        lsp.log.error(err.code, err.message)
      elseif result and result.contents then
        -- Make sure the response is not empty
        -- Five response shapes:
        -- - MarkupContent: { kind="markdown", value="doc" }
        -- - MarkedString-string: "doc"
        -- - MarkedString-pair: { language="c", value="doc" }
        -- - MarkedString[]-string: { "doc1", ... }
        -- - MarkedString[]-pair: { { language="c", value="doc1" }, ... }
        local valid = false
        if type(result.contents) == 'table' then
          local value_len = #(
            vim.tbl_get(result.contents, 'value') -- MarkupContent or MarkedString-pair
            or vim.tbl_get(result.contents, 1, 'value') -- MarkedString[]-pair
            or result.contents[1] -- MarkedString[]-string
            or ''
          )
          valid = value_len > 0
        elseif type(result.contents) == 'string' then
          valid = #result.contents > 0
        end

        if valid then
          results1[client_id] = result
          nresults = nresults + 1
        else
          empty_response = true
        end
      end
    end

    if nresults == 0 then
      if config.silent ~= true then
        if empty_response then
          vim.notify('Empty hover response', vim.log.levels.INFO)
        else
          vim.notify('No information available', vim.log.levels.INFO)
        end
      end
      return
    end

    local contents = {} --- @type string[]
    local MarkupKind = lsp.protocol.MarkupKind
    local format = MarkupKind.Markdown

    for client_id, result in pairs(results1) do
      local client = assert(lsp.get_client_by_id(client_id))
      if nresults > 1 then
        -- Show client name if there are multiple clients
        contents[#contents + 1] = string.format('# %s', client.name)
      end

      if type(result.contents) == 'table' and result.contents.kind == MarkupKind.PlainText then
        if nresults == 1 then
          -- Only one client: use PlainText format
          format = MarkupKind.PlainText
          contents = vim.split(result.contents.value or '', '\n', { trimempty = true })
        else
          -- Multiple clients: surround plaintext with ``` to get correct formatting
          contents[#contents + 1] = '```'
          vim.list_extend(
            contents,
            vim.split(result.contents.value or '', '\n', { trimempty = true })
          )
          contents[#contents + 1] = '```'
        end
      else
        vim.list_extend(contents, util.convert_input_to_markdown_lines(result.contents))
      end
      local range = result.range
      if range then
        local start = range.start
        local end_ = range['end']
        local start_idx = util._get_line_byte_from_position(bufnr, start, client.offset_encoding)
        local end_idx = util._get_line_byte_from_position(bufnr, end_, client.offset_encoding)

        vim.hl.range(
          bufnr,
          hover_ns,
          'LspReferenceTarget',
          { start.line, start_idx },
          { end_.line, end_idx },
          { priority = vim.hl.priorities.user }
        )
      end
      contents[#contents + 1] = '---'
    end

    -- Remove last linebreak ('---') if contents is not empty
    if #contents > 0 then
      contents[#contents] = nil
    end

    local _, winid = lsp.util.open_floating_preview(contents, format, config)

    api.nvim_create_autocmd('WinClosed', {
      pattern = tostring(winid),
      once = true,
      callback = function()
        api.nvim_buf_clear_namespace(bufnr, hover_ns, 0, -1)
        return true
      end,
    })
  end)
end

local function request_with_opts(name, params, opts)
  local req_handler --- @type function?
  if opts then
    req_handler = function(err, result, ctx, config)
      local client = assert(lsp.get_client_by_id(ctx.client_id))
      local handler = client.handlers[name] or lsp.handlers[name]
      handler(err, result, ctx, vim.tbl_extend('force', config or {}, opts))
    end
  end
  lsp.buf_request(0, name, params, req_handler)
end

---@param method vim.lsp.protocol.Method.ClientToServer.Request
---@param context? lsp.ReferenceContext
---@param opts? vim.lsp.ListOpts
local function get_locations(method, context, opts)
  opts = opts or {}
  ---@diagnostic disable-next-line: undefined-field
  if opts.reuse_win then
    vim.deprecate(
      'vim.lsp.buf.<method>({ reuse_win = true })',
      "vim.lsp.buf.<method>() and the value of 'switchbuf' of preference",
      '0.13'
    )
  end

  local bufnr = api.nvim_get_current_buf()
  local win = api.nvim_get_current_win()

  local clients = lsp.get_clients({ method = method, bufnr = bufnr })
  if not next(clients) then
    vim.notify(lsp._unsupported_method(method), vim.log.levels.WARN)
    return
  end

  local from = vim.fn.getpos('.')
  from[1] = bufnr
  local tagname = vim.fn.expand('<cword>')

  lsp.buf_request_all(bufnr, method, function(client)
    local params = util.make_position_params(win, client.offset_encoding)
    ---@diagnostic disable-next-line: inject-field
    params.context = context or { includeDeclaration = true }
    return params
  end, function(results)
    ---@type vim.quickfix.entry[]
    local all_items = {}

    for client_id, res in pairs(results) do
      local client = assert(lsp.get_client_by_id(client_id))
      local locations = {}
      if res then
        locations = vim.islist(res.result) and res.result or { res.result }
      end
      local items = util.locations_to_items(locations, client.offset_encoding)
      vim.list_extend(all_items, items)
    end

    local name = string.gsub(method:match('textDocument/(.*)'), '(%u)', ' %1'):lower()
    if vim.tbl_isempty(all_items) then
      vim.notify(('No %s found'):format(name), vim.log.levels.INFO)
      return
    end

    ---@type vim.fn.setqflist.what
    local what = {
      title = name:gsub('^%l', string.upper),
      items = all_items,
      context = { bufnr = bufnr, method = method },
    }
    if opts.on_list then
      validate('opts.on_list', opts.on_list, 'function')
      opts.on_list(what)
    else
      if opts.loclist then
        vim.fn.setloclist(0, {}, ' ', what)
      else
        vim.fn.setqflist({}, ' ', what)
      end

      if
        #all_items == 1
        and method ~= 'textDocument/implementation'
        and method ~= 'textDocument/references'
      then
        local tagstack = { { tagname = tagname, from = from } }
        vim.fn.settagstack(vim.fn.win_getid(win), { items = tagstack }, 't')
        if opts.loclist then
          vim.cmd('lfirst')
        else
          vim.cmd('cfirst')
        end
      else
        if opts.loclist then
          vim.cmd('botright lopen')
        else
          vim.cmd('botright copen')
        end
      end
    end
  end)
end

--- @class vim.lsp.ListOpts
---
--- list-handler replacing the default handler.
--- Called for any non-empty result.
--- The default handler populates the quickfix (or location) list with the result.
--- If there is a single result (and the method is not `implementation` or `references`),
--- it pushes a tag onto the tagstack and jumps to the result.
--- For example, when `loclist == false` (the default), the handler is equivalent to:
--- ```lua
--- local function on_list(what)
---   vim.fn.setqflist({}, ' ', what)
---   if
---     #what.items == 1
---     and what.context.method ~= 'textDocument/implementation'
---     and what.context.method ~= 'textDocument/references'
---   then
---     local tagstack = { { tagname = tagname, from = from } }
---     vim.fn.settagstack(vim.fn.win_getid(win), { items = tagstack }, 't')
---     vim.cmd('cfirst')
---   else
---     vim.cmd('botright copen')
---   end
--- end
---
--- vim.lsp.buf.definition({ on_list = on_list })
--- vim.lsp.buf.references(nil, { on_list = on_list })
--- ```
--- See |setqflist-what| for the structure of the `what` parameter.
--- @field on_list? fun(what: vim.fn.setqflist.what)
---
--- Whether to use the |location-list| or the |quickfix| list in the default handler.
--- ```lua
--- vim.lsp.buf.definition({ loclist = true })
--- vim.lsp.buf.references(nil, { loclist = false })
--- ```
--- @field loclist? boolean

--- Jumps to the declaration of the symbol under the cursor.
--- @note Many servers do not implement this method. Generally, see |vim.lsp.buf.definition()| instead.
--- @param opts? vim.lsp.ListOpts
function M.declaration(opts)
  validate('opts', opts, 'table', true)
  get_locations('textDocument/declaration', nil, opts)
end

--- Jumps to the definition of the symbol under the cursor.
--- @param opts? vim.lsp.ListOpts
function M.definition(opts)
  validate('opts', opts, 'table', true)
  get_locations('textDocument/definition', nil, opts)
end

--- Jumps to the definition of the type of the symbol under the cursor.
--- @param opts? vim.lsp.ListOpts
function M.type_definition(opts)
  validate('opts', opts, 'table', true)
  get_locations('textDocument/typeDefinition', nil, opts)
end

--- Lists all the implementations for the symbol under the cursor in the
--- quickfix window.
--- @param opts? vim.lsp.ListOpts
function M.implementation(opts)
  validate('opts', opts, 'table', true)
  get_locations('textDocument/implementation', nil, opts)
end

--- @param results table<integer,{err: lsp.ResponseError?, result: lsp.SignatureHelp?}>
local function process_signature_help_results(results)
  local signatures = {} --- @type [vim.lsp.Client,lsp.SignatureInformation][]
  local active_signature = 1

  -- Pre-process results
  for client_id, r in pairs(results) do
    local err = r.err
    local client = assert(lsp.get_client_by_id(client_id))
    if err then
      vim.notify(
        client.name .. ': ' .. tostring(err.code) .. ': ' .. err.message,
        vim.log.levels.ERROR
      )
      api.nvim_command('redraw')
    else
      local result = r.result
      if result and result.signatures then
        for i, sig in ipairs(result.signatures) do
          sig.activeParameter = sig.activeParameter or result.activeParameter
          local idx = #signatures + 1
          if (result.activeSignature or 0) + 1 == i then
            active_signature = idx
          end
          signatures[idx] = { client, sig }
        end
      end
    end
  end

  return signatures, active_signature
end

local sig_help_ns = api.nvim_create_namespace('nvim.lsp.signature_help')

--- @class vim.lsp.buf.signature_help.Opts : vim.lsp.util.open_floating_preview.Opts
--- @field silent? boolean

--- Displays signature information about the symbol under the cursor in a
--- floating window. Allows cycling through signature overloads with `<C-s>`,
--- which can be remapped via `<Plug>(nvim.lsp.ctrl-s)`
---
--- Example:
---
--- ```lua
--- vim.keymap.set('n', '<C-b>', '<Plug>(nvim.lsp.ctrl-s)')
--- ```
---
--- @param config? vim.lsp.buf.signature_help.Opts
function M.signature_help(config)
  validate('config', config, 'table', true)

  local method = 'textDocument/signatureHelp'

  config = config and vim.deepcopy(config) or {}
  config.focus_id = method
  local user_title = config.title

  lsp.buf_request_all(0, method, client_positional_params(), function(results, ctx)
    if not ctx_is_valid(ctx) then
      return -- Ignore result if context changed. Can happen for slow LS.
    end

    local signatures, active_signature = process_signature_help_results(results)

    if not next(signatures) then
      if config.silent ~= true then
        vim.notify('No signature help available', vim.log.levels.INFO)
      end
      return
    end

    local ft = vim.bo[ctx.bufnr].filetype
    local total = #signatures
    local can_cycle = total > 1 and config.focusable ~= false
    local idx = active_signature - 1

    --- @param update_win? integer
    local function show_signature(update_win)
      idx = (idx % total) + 1
      local client, result = signatures[idx][1], signatures[idx][2]
      --- @type string[]?
      local triggers =
        vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters')
      local lines, hl =
        util.convert_signature_help_to_markdown_lines({ signatures = { result } }, ft, triggers)
      if not lines then
        return
      end

      -- Show title only if there are multiple clients or multiple signatures.
      if total > 1 then
        local sfx = total > 1
            and string.format(' (%d/%d)%s', idx, total, can_cycle and ' (<C-s> to cycle)' or '')
          or ''
        config.title = user_title or string.format('Signature Help: %s%s', client.name, sfx)
        -- If no border is set, render title inside the window.
        if not (config.border or vim.o.winborder ~= '') then
          table.insert(lines, 1, '# ' .. config.title)
          if hl then
            hl[1] = hl[1] + 1
            hl[3] = hl[3] + 1
          end
        end
      end

      config._update_win = update_win

      local buf, win = util.open_floating_preview(lines, 'markdown', config)

      if hl then
        api.nvim_buf_clear_namespace(buf, sig_help_ns, 0, -1)
        vim.hl.range(
          buf,
          sig_help_ns,
          'LspSignatureActiveParameter',
          { hl[1], hl[2] },
          { hl[3], hl[4] }
        )
      end
      return buf, win
    end

    local fbuf, fwin = show_signature()

    if can_cycle then
      vim.keymap.set('n', '<Plug>(nvim.lsp.ctrl-s)', function()
        show_signature(fwin)
      end, {
        buf = fbuf,
        desc = 'Cycle next signature',
      })
      if vim.fn.hasmapto('<Plug>(nvim.lsp.ctrl-s)', 'n') == 0 then
        vim.keymap.set('n', '<C-s>', '<Plug>(nvim.lsp.ctrl-s)', {
          buf = fbuf,
          desc = 'Cycle next signature',
        })
      end
    end
  end)
end

--- @deprecated
--- Retrieves the completion items at the current cursor position. Can only be
--- called in Insert mode.
---
---@param context table (context support not yet implemented) Additional information
--- about the context in which a completion was triggered (how it was triggered,
--- and by which trigger character, if applicable)
---
---@see vim.lsp.protocol.CompletionTriggerKind
function M.completion(context)
  validate('context', context, 'table', true)
  vim.deprecate('vim.lsp.buf.completion', 'vim.lsp.completion.trigger', '0.12')
  return lsp.buf_request(
    0,
    'textDocument/completion',
    client_positional_params({
      context = context,
    })
  )
end

---@param bufnr integer
---@param mode "v"|"V"
---@return table {start={row,col}, end={row,col}} using (1, 0) indexing
local function range_from_selection(bufnr, mode)
  -- TODO: Use `vim.fn.getregionpos()` instead.

  -- [bufnum, lnum, col, off]; both row and column 1-indexed
  local start = vim.fn.getpos('v')
  local end_ = vim.fn.getpos('.')
  local start_row = start[2]
  local start_col = start[3]
  local end_row = end_[2]
  local end_col = end_[3]

  -- A user can start visual selection at the end and move backwards
  -- Normalize the range to start < end
  if start_row == end_row and end_col < start_col then
    end_col, start_col = start_col, end_col --- @type integer, integer
  elseif end_row < start_row then
    start_row, end_row = end_row, start_row --- @type integer, integer
    start_col, end_col = end_col, start_col --- @type integer, integer
  end
  if mode == 'V' then
    start_col = 1
    local lines = api.nvim_buf_get_lines(bufnr, end_row - 1, end_row, true)
    end_col = #lines[1]
  end
  return {
    ['start'] = { start_row, start_col - 1 },
    ['end'] = { end_row, end_col - 1 },
  }
end

--- @class vim.lsp.buf.format.Opts
--- @inlinedoc
---
--- Can be used to specify FormattingOptions. Some unspecified options will be
--- automatically derived from the current Nvim options.
--- See https://microsoft.github.io/language-server-protocol/specification/#formattingOptions
--- @field formatting_options? lsp.FormattingOptions
---
--- Time in milliseconds to block for formatting requests. No effect if async=true.
--- (default: `1000`)
--- @field timeout_ms? integer
---
--- Restrict formatting to the clients attached to the given buffer.
--- (default: current buffer)
--- @field bufnr? integer
---
--- Predicate used to filter clients. Receives a client as argument and must
--- return a boolean. Clients matching the predicate are included. Example:
--- ```lua
--- -- Never request typescript-language-server for formatting
--- vim.lsp.buf.format {
---   filter = function(client) return client.name ~= "ts_ls" end
--- }
--- ```
--- @field filter? fun(client: vim.lsp.Client): boolean?
---
--- If true the method won't block.
--- Editing the buffer while formatting asynchronous can lead to unexpected
--- changes.
--- (Default: false)
--- @field async? boolean
---
--- Restrict formatting to the client with ID (client.id) matching this field.
--- @field id? integer
---
--- Restrict formatting to the client with name (client.name) matching this field.
--- @field name? string
---
--- Range to format.
--- Table must contain `start` and `end` keys with {row,col} tuples using
--- (1,0) indexing.
--- Can also be a list of tables that contain `start` and `end` keys as described above,
--- in which case `textDocument/rangesFormatting` support is required.
--- (Default: current selection in visual mode, `nil` in other modes,
--- formatting the full buffer)
--- @field range? {start:[integer,integer],end:[integer, integer]}|{start:[integer,integer],end:[integer,integer]}[]

--- Formats a buffer using the attached (and optionally filtered) language
--- server clients.
---
--- @param opts? vim.lsp.buf.format.Opts
function M.format(opts)
  validate('opts', opts, 'table', true)

  opts = opts or {}
  local bufnr = vim._resolve_bufnr(opts.bufnr)
  local mode = api.nvim_get_mode().mode
  local range = opts.range
  -- Try to use visual selection if no range is given
  if not range and mode == 'v' or mode == 'V' then
    range = range_from_selection(bufnr, mode)
  end

  local passed_multiple_ranges = (range and #range ~= 0 and type(range[1]) == 'table')
  local method ---@type vim.lsp.protocol.Method.ClientToServer.Request
  if passed_multiple_ranges then
    method = 'textDocument/rangesFormatting'
  elseif range then
    method = 'textDocument/rangeFormatting'
  else
    method = 'textDocument/formatting'
  end

  local clients = lsp.get_clients({
    id = opts.id,
    bufnr = bufnr,
    name = opts.name,
    method = method,
  })
  if opts.filter then
    clients = vim.tbl_filter(opts.filter, clients)
  end

  if #clients == 0 then
    vim.notify('[LSP] Format request failed, no matching language servers.')
  end

  --- @param client vim.lsp.Client
  --- @param params lsp.DocumentFormattingParams
  --- @return lsp.DocumentFormattingParams|lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams
  local function set_range(client, params)
    ---  @param r {start:[integer,integer],end:[integer, integer]}
    local function to_lsp_range(r)
      return util.make_given_range_params(r.start, r['end'], bufnr, client.offset_encoding).range
    end

    local ret = params --[[@as lsp.DocumentFormattingParams|lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams]]
    if passed_multiple_ranges then
      --- @cast range {start:[integer,integer],end:[integer, integer]}[]
      ret = params --[[@as lsp.DocumentRangesFormattingParams]]
      ret.ranges = vim.tbl_map(to_lsp_range, range)
    elseif range then
      --- @cast range {start:[integer,integer],end:[integer, integer]}
      ret = params --[[@as lsp.DocumentRangeFormattingParams]]
      ret.range = to_lsp_range(range)
    end
    return ret
  end

  if opts.async then
    --- @param idx? integer
    --- @param client? vim.lsp.Client
    local function do_format(idx, client)
      if not idx or not client then
        return
      end
      local params = set_range(client, util.make_formatting_params(opts.formatting_options))
      client:request(method, params, function(...)
        local handler = client.handlers[method] or lsp.handlers[method]
        handler(...)
        do_format(next(clients, idx))
      end, bufnr)
    end
    do_format(next(clients))
  else
    local timeout_ms = opts.timeout_ms or 1000
    for _, client in pairs(clients) do
      local params = set_range(client, util.make_formatting_params(opts.formatting_options))
      local result, err = client:request_sync(method, params, timeout_ms, bufnr)
      if result and result.result then
        util.apply_text_edits(result.result, bufnr, client.offset_encoding)
      elseif err then
        vim.notify(string.format('[LSP][%s] %s', client.name, err), vim.log.levels.WARN)
      end
    end
  end
end

--- @class vim.lsp.buf.rename.Opts
--- @inlinedoc
---
--- Predicate used to filter clients. Receives a client as argument and
--- must return a boolean. Clients matching the predicate are included.
--- @field filter? fun(client: vim.lsp.Client): boolean?
---
--- Restrict clients used for rename to ones where client.name matches
--- this field.
--- @field name? string
---
--- (default: current buffer)
--- @field bufnr? integer

--- Renames all references to the symbol under the cursor.
---
---@param new_name string|nil If not provided, the user will be prompted for a new
---                name using |vim.ui.input()|.
---@param opts? vim.lsp.buf.rename.Opts Additional options:
function M.rename(new_name, opts)
  validate('new_name', new_name, 'string', true)
  validate('opts', opts, 'table', true)

  opts = opts or {}
  local bufnr = vim._resolve_bufnr(opts.bufnr)
  local clients = lsp.get_clients({
    bufnr = bufnr,
    name = opts.name,
    -- Clients must at least support rename, prepareRename is optional
    method = 'textDocument/rename',
  })
  if opts.filter then
    clients = vim.tbl_filter(opts.filter, clients)
  end

  if #clients == 0 then
    vim.notify('[LSP] Rename, no matching language servers with rename capability.')
  end

  local win = api.nvim_get_current_win()

  -- Compute early to account for cursor movements after going async
  local cword = vim.fn.expand('<cword>')

  --- @param range lsp.Range
  --- @param position_encoding 'utf-8'|'utf-16'|'utf-32'
  local function get_text_at_range(range, position_encoding)
    return api.nvim_buf_get_text(
      bufnr,
      range.start.line,
      util._get_line_byte_from_position(bufnr, range.start, position_encoding),
      range['end'].line,
      util._get_line_byte_from_position(bufnr, range['end'], position_encoding),
      {}
    )[1]
  end

  --- @param idx? integer
  --- @param client? vim.lsp.Client
  local function try_use_client(idx, client)
    if not idx or not client then
      return
    end

    --- @param name string
    local function rename(name)
      local params = util.make_position_params(win, client.offset_encoding) --[[@as lsp.RenameParams]]
      params.newName = name
      local handler = client.handlers['textDocument/rename'] or lsp.handlers['textDocument/rename']
      client:request('textDocument/rename', params, function(...)
        handler(...)
        try_use_client(next(clients, idx))
      end, bufnr)
    end

    if client:supports_method('textDocument/prepareRename') then
      local params = util.make_position_params(win, client.offset_encoding)
      ---@param result? lsp.Range|{ range: lsp.Range, placeholder: string }
      client:request('textDocument/prepareRename', params, function(err, result)
        if err or result == nil then
          if next(clients, idx) then
            try_use_client(next(clients, idx))
          else
            local msg = err and ('Error on prepareRename: ' .. (err.message or ''))
              or 'Nothing to rename'
            vim.notify(msg, vim.log.levels.INFO)
          end
          return
        end

        if new_name then
          rename(new_name)
          return
        end

        local range ---@type lsp.Range?
        if result.start then
          ---@cast result lsp.Range
          range = result
        elseif result.range then
          ---@cast result { range: lsp.Range, placeholder: string }
          range = result.range
        end
        if range then
          local start = range.start
          local end_ = range['end']
          local start_idx = util._get_line_byte_from_position(bufnr, start, client.offset_encoding)
          local end_idx = util._get_line_byte_from_position(bufnr, end_, client.offset_encoding)

          vim.hl.range(
            bufnr,
            rename_ns,
            'LspReferenceTarget',
            { start.line, start_idx },
            { end_.line, end_idx },
            { priority = vim.hl.priorities.user }
          )
        end

        local prompt_opts = {
          prompt = 'New Name: ',
        }
        if result.placeholder then
          prompt_opts.default = result.placeholder
        elseif result.start then
          prompt_opts.default = get_text_at_range(result, client.offset_encoding)
        elseif result.range then
          prompt_opts.default = get_text_at_range(result.range, client.offset_encoding)
        else
          prompt_opts.default = cword
        end
        vim.ui.input(prompt_opts, function(input)
          if input and #input ~= 0 then
            rename(input)
          end
          api.nvim_buf_clear_namespace(bufnr, rename_ns, 0, -1)
        end)
      end, bufnr)
    else
      assert(
        client:supports_method('textDocument/rename'),
        'Client must support textDocument/rename'
      )
      if new_name then
        rename(new_name)
        return
      end

      local prompt_opts = {
        prompt = 'New Name: ',
        default = cword,
      }
      vim.ui.input(prompt_opts, function(input)
        if not input or #input == 0 then
          return
        end
        rename(input)
      end)
    end
  end

  try_use_client(next(clients))
end

--- Lists all the references to the symbol under the cursor in the quickfix window.
---
---@param context lsp.ReferenceContext? Context for the request
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references
---@param opts? vim.lsp.ListOpts
function M.references(context, opts)
  validate('context', context, 'table', true)
  validate('opts', opts, 'table', true)
  get_locations('textDocument/references', context, opts)
end

--- Lists all symbols in the current buffer in the |location-list|.
--- @param opts? vim.lsp.ListOpts
function M.document_symbol(opts)
  validate('opts', opts, 'table', true)
  opts = vim.tbl_deep_extend('keep', opts or {}, { loclist = true })
  local params = { textDocument = util.make_text_document_params() }
  request_with_opts('textDocument/documentSymbol', params, opts)
end

--- @param client_id integer
--- @param method vim.lsp.protocol.Method.ClientToServer.Request
--- @param params table
--- @param handler? lsp.Handler
--- @param bufnr? integer
local function request_with_id(client_id, method, params, handler, bufnr)
  local client = lsp.get_client_by_id(client_id)
  if not client then
    vim.notify(
      string.format('Client with id=%d disappeared during hierarchy request', client_id),
      vim.log.levels.WARN
    )
    return
  end
  client:request(method, params, handler, bufnr)
end

--- @param item lsp.TypeHierarchyItem|lsp.CallHierarchyItem
local function format_hierarchy_item(item)
  if not item.detail or #item.detail == 0 then
    return item.name
  end
  return string.format('%s %s', item.name, item.detail)
end

--- @alias vim.lsp.buf.HierarchyMethod
--- | 'typeHierarchy/subtypes'
--- | 'typeHierarchy/supertypes'
--- | 'callHierarchy/incomingCalls'
--- | 'callHierarchy/outgoingCalls'

--- @type table<vim.lsp.buf.HierarchyMethod, 'type' | 'call'>
local hierarchy_methods = {
  ['typeHierarchy/subtypes'] = 'type',
  ['typeHierarchy/supertypes'] = 'type',
  ['callHierarchy/incomingCalls'] = 'call',
  ['callHierarchy/outgoingCalls'] = 'call',
}

--- @param method vim.lsp.buf.HierarchyMethod
local function hierarchy(method)
  local kind = hierarchy_methods[method]

  local prepare_method = kind == 'type' and 'textDocument/prepareTypeHierarchy'
    or 'textDocument/prepareCallHierarchy'

  local bufnr = api.nvim_get_current_buf()
  local clients = lsp.get_clients({ bufnr = bufnr, method = prepare_method })
  if not next(clients) then
    vim.notify(lsp._unsupported_method(method), vim.log.levels.WARN)
    return
  end

  local win = api.nvim_get_current_win()

  lsp.buf_request_all(bufnr, prepare_method, function(client)
    return util.make_position_params(win, client.offset_encoding)
  end, function(req_results)
    local results = {} --- @type [integer, lsp.TypeHierarchyItem|lsp.CallHierarchyItem][]
    for client_id, res in pairs(req_results) do
      if res.err then
        vim.notify(res.err.message, vim.log.levels.WARN)
      elseif res.result then
        local result = res.result --- @type lsp.TypeHierarchyItem[]|lsp.CallHierarchyItem[]
        for _, item in ipairs(result) do
          results[#results + 1] = { client_id, item }
        end
      end
    end

    if #results == 0 then
      vim.notify('No item resolved', vim.log.levels.WARN)
    elseif #results == 1 then
      local client_id, item = results[1][1], results[1][2]
      request_with_id(client_id, method, { item = item }, nil, bufnr)
    else
      vim.ui.select(results, {
        prompt = string.format('Select a %s hierarchy item:', kind),
        kind = kind .. 'hierarchy',
        format_item = function(x)
          return format_hierarchy_item(x[2])
        end,
      }, function(x)
        if x then
          local client_id, item = x[1], x[2]
          request_with_id(client_id, method, { item = item }, nil, bufnr)
        end
      end)
    end
  end)
end

--- Lists all the call sites of the symbol under the cursor in the
--- |quickfix| window. If the symbol can resolve to multiple
--- items, the user can pick one in the |inputlist()|.
function M.incoming_calls()
  hierarchy('callHierarchy/incomingCalls')
end

--- Lists all the items that are called by the symbol under the
--- cursor in the |quickfix| window. If the symbol can resolve to
--- multiple items, the user can pick one in the |inputlist()|.
function M.outgoing_calls()
  hierarchy('callHierarchy/outgoingCalls')
end

--- Lists all the subtypes or supertypes of the symbol under the
--- cursor in the |quickfix| window. If the symbol can resolve to
--- multiple items, the user can pick one using |vim.ui.select()|.
---@param kind "subtypes"|"supertypes"
function M.typehierarchy(kind)
  validate('kind', kind, function(v)
    return v == 'subtypes' or v == 'supertypes'
  end)

  local method = kind == 'subtypes' and 'typeHierarchy/subtypes' or 'typeHierarchy/supertypes'
  hierarchy(method)
end

--- List workspace folders.
---
function M.list_workspace_folders()
  local workspace_folders = {}
  for _, client in pairs(lsp.get_clients({ bufnr = 0 })) do
    for _, folder in pairs(client.workspace_folders or {}) do
      table.insert(workspace_folders, folder.name)
    end
  end
  return workspace_folders
end

--- Add the folder at path to the workspace folders. If {path} is
--- not provided, the user will be prompted for a path using |input()|.
--- @param workspace_folder? string
function M.add_workspace_folder(workspace_folder)
  validate('workspace_folder', workspace_folder, 'string', true)

  workspace_folder = workspace_folder
    or npcall(vim.fn.input, 'Workspace Folder: ', vim.fn.expand('%:p:h'), 'dir')
  api.nvim_command('redraw')
  if not (workspace_folder and #workspace_folder > 0) then
    return
  end
  if vim.fn.isdirectory(workspace_folder) == 0 then
    vim.notify(workspace_folder .. ' is not a valid directory')
    return
  end
  local bufnr = api.nvim_get_current_buf()
  for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do
    client:_add_workspace_folder(workspace_folder)
  end
end

--- Remove the folder at path from the workspace folders. If
--- {path} is not provided, the user will be prompted for
--- a path using |input()|.
--- @param workspace_folder? string
function M.remove_workspace_folder(workspace_folder)
  validate('workspace_folder', workspace_folder, 'string', true)

  workspace_folder = workspace_folder
    or npcall(vim.fn.input, 'Workspace Folder: ', vim.fn.expand('%:p:h'))
  api.nvim_command('redraw')
  if not workspace_folder or #workspace_folder == 0 then
    return
  end
  local bufnr = api.nvim_get_current_buf()
  for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do
    client:_remove_workspace_folder(workspace_folder)
  end
  vim.notify(workspace_folder .. 'is not currently part of the workspace')
end

--- Lists all symbols in the current workspace in the quickfix window.
---
--- The list is filtered against {query}; if the argument is omitted from the
--- call, the user is prompted to enter a string on the command line. An empty
--- string means no filtering is done.
---
--- @param query string? optional
--- @param opts? vim.lsp.ListOpts
function M.workspace_symbol(query, opts)
  validate('query', query, 'string', true)
  validate('opts', opts, 'table', true)

  query = query or npcall(vim.fn.input, 'Query: ')
  if query == nil then
    return
  end
  local params = { query = query }
  request_with_opts('workspace/symbol', params, opts)
end

--- @class vim.lsp.WorkspaceDiagnosticsOpts
--- @inlinedoc
---
--- Only request diagnostics from the indicated client. If nil, the request is sent to all clients.
--- @field client_id? integer

--- Request workspace-wide diagnostics.
--- @param opts? vim.lsp.WorkspaceDiagnosticsOpts
--- @see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_dagnostics
function M.workspace_diagnostics(opts)
  validate('opts', opts, 'table', true)

  lsp.diagnostic._workspace_diagnostics(opts or {})
end

--- Send request to the server to resolve document highlights for the current
--- text document position. This request can be triggered by a  key mapping or
--- by events such as `CursorHold`, e.g.:
---
--- ```vim
--- autocmd CursorHold  <buffer> lua vim.lsp.buf.document_highlight()
--- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight()
--- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
--- ```
---
--- Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups
---       to be defined or you won't be able to see the actual highlights.
---         |hl-LspReferenceText|
---         |hl-LspReferenceRead|
---         |hl-LspReferenceWrite|
function M.document_highlight()
  lsp.buf_request(0, 'textDocument/documentHighlight', client_positional_params())
end

--- Removes document highlights from current buffer.
function M.clear_references()
  util.buf_clear_references()
end

---@nodoc
---@class vim.lsp.CodeActionResultEntry
---@field err? lsp.ResponseError
---@field result? (lsp.Command|lsp.CodeAction)[]
---@field context lsp.HandlerContext

--- @class vim.lsp.buf.code_action.Opts
--- @inlinedoc
---
--- Corresponds to `CodeActionContext` of the LSP specification:
---   - {diagnostics}? (`table`) LSP `Diagnostic[]`. Inferred from the current
---     position if not provided.
---   - {only}? (`table`) List of LSP `CodeActionKind`s used to filter the code actions.
---     Most language servers support values like `refactor`
---     or `quickfix`.
---   - {triggerKind}? (`integer`) The reason why code actions were requested.
--- @field context? lsp.CodeActionContext
---
--- Predicate taking a code action or command and the provider's ID.
--- If it returns false, the action is filtered out.
--- @field filter? fun(x: lsp.CodeAction|lsp.Command, client_id: integer):boolean
---
--- When set to `true`, and there is just one remaining action
--- (after filtering), the action is applied without user query.
--- @field apply? boolean
---
--- Range for which code actions should be requested.
--- If in visual mode this defaults to the active selection.
--- Table must contain `start` and `end` keys with {row,col} tuples
--- using mark-like indexing. See |api-indexing|
--- @field range? {start: integer[], end: integer[]}

--- This is not public because the main extension point is
--- vim.ui.select which can be overridden independently.
---
--- Can't call/use vim.lsp.handlers['textDocument/codeAction'] because it expects
--- `(err, CodeAction[] | Command[], ctx)`, but we want to aggregate the results
--- from multiple clients to have 1 single UI prompt for the user, yet we still
--- need to be able to link a `CodeAction|Command` to the right client for
--- `codeAction/resolve`
---@param results table<integer, vim.lsp.CodeActionResultEntry>
---@param opts? vim.lsp.buf.code_action.Opts
local function on_code_action_results(results, opts)
  ---@param a lsp.Command|lsp.CodeAction
  ---@param client_id integer
  local function action_filter(a, client_id)
    -- filter by specified action kind
    if opts and opts.context then
      if opts.context.only then
        if not a.kind then
          return false
        end
        local found = false
        for _, o in ipairs(opts.context.only) do
          -- action kinds are hierarchical with . as a separator: when requesting only 'type-annotate'
          -- this filter allows both 'type-annotate' and 'type-annotate.foo', for example
          if a.kind == o or vim.startswith(a.kind, o .. '.') then
            found = true
            break
          end
        end
        if not found then
          return false
        end
      end
      -- Only show disabled code actions when the trigger kind is "Invoked".
      if a.disabled and opts.context.triggerKind ~= lsp.protocol.CodeActionTriggerKind.Invoked then
        return false
      end
    end
    -- filter by user function
    if opts and opts.filter and not opts.filter(a, client_id) then
      return false
    end
    -- no filter removed this action
    return true
  end

  ---@type {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}[]
  local actions = {}
  for _, result in pairs(results) do
    for _, action in pairs(result.result or {}) do
      if action_filter(action, result.context.client_id) then
        table.insert(actions, { action = action, ctx = result.context })
      end
    end
  end
  if #actions == 0 then
    vim.notify('No code actions available', vim.log.levels.INFO)
    return
  end

  ---@param action lsp.Command|lsp.CodeAction
  ---@param client vim.lsp.Client
  ---@param ctx lsp.HandlerContext
  local function apply_action(action, client, ctx)
    if action.edit then
      util.apply_workspace_edit(action.edit, client.offset_encoding)
    end
    local a_cmd = action.command
    if a_cmd then
      local command = type(a_cmd) == 'table' and a_cmd or action
      --- @cast command lsp.Command
      client:exec_cmd(command, ctx)
    end
  end

  ---@param choice {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}
  local function on_user_choice(choice)
    if not choice then
      return
    end

    -- textDocument/codeAction can return either Command[] or CodeAction[]
    --
    -- CodeAction
    --  ...
    --  edit?: WorkspaceEdit    -- <- must be applied before command
    --  command?: Command
    --
    -- Command:
    --  title: string
    --  command: string
    --  arguments?: any[]

    local client = assert(lsp.get_client_by_id(choice.ctx.client_id))
    local action = choice.action
    local bufnr = assert(choice.ctx.bufnr, 'Must have buffer number')

    -- Only code actions are resolved, so if we have a command, just apply it.
    if type(action.title) == 'string' and type(action.command) == 'string' then
      apply_action(action, client, choice.ctx)
      return
    end

    if action.disabled then
      vim.notify(action.disabled.reason, vim.log.levels.ERROR)
      return
    end

    if not (action.edit and action.command) and client:supports_method('codeAction/resolve') then
      client:request('codeAction/resolve', action, function(err, resolved_action)
        if err then
          -- If resolve fails, try to apply the edit/command from the original code action.
          if action.edit or action.command then
            apply_action(action, client, choice.ctx)
          else
            vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR)
          end
        else
          apply_action(resolved_action, client, choice.ctx)
        end
      end, bufnr)
    else
      apply_action(action, client, choice.ctx)
    end
  end

  -- If options.apply is given, and there are just one remaining code action,
  -- apply it directly without querying the user.
  if opts and opts.apply and #actions == 1 then
    on_user_choice(actions[1])
    return
  end

  ---@param item {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}
  local function format_item(item)
    local clients = lsp.get_clients({ bufnr = item.ctx.bufnr })
    local title = item.action.title:gsub('\r\n', '\\r\\n'):gsub('\n', '\\n')

    if item.action.disabled then
      title = title .. ' (disabled)'
    end

    if #clients == 1 then
      return title
    end

    local source = assert(lsp.get_client_by_id(item.ctx.client_id)).name
    return ('%s [%s]'):format(title, source)
  end

  local select_opts = {
    prompt = 'Code actions:',
    kind = 'codeaction',
    format_item = format_item,
  }
  vim.ui.select(actions, select_opts, on_user_choice)
end

--- Selects a code action (LSP: "textDocument/codeAction" request) available at cursor position.
---
---@param opts? vim.lsp.buf.code_action.Opts
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction
---@see vim.lsp.protocol.CodeActionTriggerKind
function M.code_action(opts)
  validate('options', opts, 'table', true)
  opts = opts or {}
  -- Detect old API call code_action(context) which should now be
  -- code_action({ context = context} )
  --- @diagnostic disable-next-line:undefined-field
  if opts.diagnostics or opts.only then
    opts = { options = opts }
  end
  local context = opts.context and vim.deepcopy(opts.context) or {}
  if not context.triggerKind then
    context.triggerKind = lsp.protocol.CodeActionTriggerKind.Invoked
  end
  local mode = api.nvim_get_mode().mode
  local bufnr = api.nvim_get_current_buf()
  local win = api.nvim_get_current_win()
  local clients = lsp.get_clients({ bufnr = bufnr, method = 'textDocument/codeAction' })
  if not next(clients) then
    vim.notify(lsp._unsupported_method('textDocument/codeAction'), vim.log.levels.WARN)
    return
  end

  lsp.buf_request_all(bufnr, 'textDocument/codeAction', function(client)
    ---@type lsp.CodeActionParams
    local params

    if opts.range then
      assert(type(opts.range) == 'table', 'code_action range must be a table')
      local start = assert(opts.range.start, 'range must have a `start` property')
      local end_ = assert(opts.range['end'], 'range must have a `end` property')
      params = util.make_given_range_params(start, end_, bufnr, client.offset_encoding)
    elseif mode == 'v' or mode == 'V' then
      local range = range_from_selection(bufnr, mode)
      params =
        util.make_given_range_params(range.start, range['end'], bufnr, client.offset_encoding)
    else
      params = util.make_range_params(win, client.offset_encoding)
    end

    --- @cast params lsp.CodeActionParams

    if context.diagnostics then
      params.context = context
    else
      local ns_push = lsp.diagnostic.get_namespace(client.id)
      local diagnostics = {}
      local lnum = api.nvim_win_get_cursor(0)[1] - 1

      client:_provider_foreach('textDocument/diagnostic', function(cap)
        local ns_pull = lsp.diagnostic.get_namespace(client.id, true, cap.identifier)
        vim.list_extend(
          diagnostics,
          vim.diagnostic.get(bufnr, { namespace = ns_pull, lnum = lnum })
        )
      end)

      vim.list_extend(diagnostics, vim.diagnostic.get(bufnr, { namespace = ns_push, lnum = lnum }))
      params.context = vim.tbl_extend('force', context, {
        ---@diagnostic disable-next-line: no-unknown
        diagnostics = vim.tbl_map(function(d)
          return d.user_data.lsp
        end, diagnostics),
      })
    end

    return params
  end, function(results)
    on_code_action_results(results, opts)
  end)
end

--- @deprecated
--- Executes an LSP server command.
--- @param command_params lsp.ExecuteCommandParams
--- @see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand
function M.execute_command(command_params)
  validate('command', command_params.command, 'string')
  validate('arguments', command_params.arguments, 'table', true)
  vim.deprecate('execute_command', 'client:exec_cmd', '0.12')
  command_params = {
    command = command_params.command,
    arguments = command_params.arguments,
    workDoneToken = command_params.workDoneToken,
  }
  lsp.buf_request(0, 'workspace/executeCommand', command_params)
end

---@type { index: integer, ranges: lsp.Range[] }?
local selection_ranges = nil

---@param range lsp.Range
local function select_range(range)
  local start_line = range.start.line + 1
  local end_line = range['end'].line + 1

  local start_col = range.start.character
  local end_col = range['end'].character

  -- If the selection ends at column 0, adjust the position to the end of the previous line.
  if end_col == 0 then
    end_line = end_line - 1
    local end_line_text = api.nvim_buf_get_lines(0, end_line - 1, end_line, true)[1]
    end_col = #end_line_text
  end

  vim.fn.setpos("'<", { 0, start_line, start_col + 1, 0 })
  vim.fn.setpos("'>", { 0, end_line, end_col, 0 })
  vim.cmd.normal({ 'gv', bang = true })
end

---@param range lsp.Range
local function is_empty(range)
  return range.start.line == range['end'].line and range.start.character == range['end'].character
end

--- Perform an incremental selection at the cursor position based on ranges given by the LSP. The
--- `direction` parameter specifies the number of times to expand the selection. Negative values
--- will shrink the selection.
---
--- @param direction integer
--- @param timeout_ms integer? (default: `1000`) Maximum time (milliseconds) to wait for a result.
function M.selection_range(direction, timeout_ms)
  validate('direction', direction, 'number')
  validate('timeout_ms', timeout_ms, 'number', true)

  if selection_ranges then
    local new_index = selection_ranges.index + direction
    selection_ranges.index = math.min(#selection_ranges.ranges, math.max(1, new_index))

    select_range(selection_ranges.ranges[selection_ranges.index])
    return
  end

  local method = 'textDocument/selectionRange'
  local client = lsp.get_clients({ method = method, bufnr = 0 })[1]
  if not client then
    vim.notify(lsp._unsupported_method(method), vim.log.levels.WARN)
    return
  end

  local position_params = util.make_position_params(0, client.offset_encoding)

  ---@type lsp.SelectionRangeParams
  local params = {
    textDocument = position_params.textDocument,
    positions = { position_params.position },
  }

  timeout_ms = timeout_ms or 1000
  local result, err = lsp.buf_request_sync(0, method, params, timeout_ms)
  if err then
    local err_message = type(err) == 'table' and lsp.rpc.format_rpc_error(err) or err
    lsp.log.error('selectionRange request failed: ' .. err_message)
    return
  end
  if not result or not result[client.id] or not result[client.id].result then
    return
  end
  if result[client.id].error then
    lsp.log.error(result[client.id].error.code, result[client.id].error.message)
  end

  -- We only requested one range, thus we get the first and only response here.
  local response = assert(result[client.id].result[1]) ---@type lsp.SelectionRange
  local ranges = {} ---@type lsp.Range[]
  local lines = api.nvim_buf_get_lines(0, 0, -1, false)

  -- Populate the list of ranges from the given request.
  while response do
    local range = response.range
    if not is_empty(range) then
      local start_line = range.start.line
      local end_line = range['end'].line
      range.start.character = vim.str_byteindex(
        lines[start_line + 1] or '',
        client.offset_encoding,
        range.start.character,
        false
      )
      range['end'].character = vim.str_byteindex(
        lines[end_line + 1] or '',
        client.offset_encoding,
        range['end'].character,
        false
      )
      ranges[#ranges + 1] = range
    end
    response = response.parent
  end

  -- Clear selection ranges when leaving visual mode.
  api.nvim_create_autocmd('ModeChanged', {
    once = true,
    pattern = 'v*:*',
    callback = function()
      selection_ranges = nil
    end,
  })

  if #ranges > 0 then
    local index = math.min(#ranges, math.max(1, direction))
    selection_ranges = { index = index, ranges = ranges }
    select_range(ranges[index])
  end
end

return M