| 🛟 Updated. 28d5985 k33g 6h ago | 1 | package app |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | |
| 6 | "codeberg.org/turbo-editors/turbo-core/lsp" |
| 7 | ) |
| 8 | |
| 9 | // RequestCompletion asks the language server what could be typed here and |
| 10 | // opens the popup with the answer. |
| 11 | // |
| 12 | // It is deliberately synchronous: the request has its own short timeout, and a |
| 13 | // completion that arrives after the user has typed three more characters is |
| 14 | // worse than none at all. |
| 15 | func (a *App) RequestCompletion() { |
| 16 | view := a.activeView() |
| 17 | if view == nil { |
| 18 | return |
| 19 | } |
| 20 | if !a.language.Ready() { |
| 21 | a.Message(a.language.Status()) |
| 22 | return |
| 23 | } |
| 24 | |
| 25 | buf := view.Buffer() |
| 26 | cursor := buf.Cursor() |
| 27 | |
| 28 | items, err := a.language.Complete(context.Background(), |
| 29 | buf.Path(), cursor.Line, cursor.Col, buf.Line(cursor.Line)) |
| 30 | if err != nil { |
| 31 | a.Message("Completion: " + err.Error()) |
| 32 | return |
| 33 | } |
| 34 | if len(items) == 0 { |
| 35 | a.Message(a.noCompletionsReason(buf.Path())) |
| 36 | return |
| 37 | } |
| 38 | |
| 39 | x, y := view.CursorScreenPosition() |
| 40 | a.completion.Show(items, view.WordBeforeCursor(), x, y, a.screenRect()) |
| 41 | } |
| 42 | |
| 43 | // refreshCompletionPrefix narrows the open popup as the user keeps typing. |
| 44 | func (a *App) refreshCompletionPrefix() { |
| 45 | if !a.completion.Visible() { |
| 46 | return |
| 47 | } |
| 48 | if view := a.activeView(); view != nil { |
| 49 | a.completion.SetPrefix(view.WordBeforeCursor()) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // acceptCompletion puts the chosen suggestion into the buffer, replacing the |
| 54 | // part of the word that had already been typed. |
| 55 | func (a *App) acceptCompletion(item lsp.CompletionItem) { |
| 56 | if view := a.activeView(); view != nil { |
| 57 | view.ReplaceWordBeforeCursor(item.Insertion()) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // noCompletionsReason explains an empty completion list. |
| 62 | // |
| 63 | // A language server answers nothing at all — no error, just an empty list — |
| 64 | // for a package it cannot load, which is what a duplicate declaration or an |
| 65 | // unresolved import produces. Saying "no completions" and stopping there |
| 66 | // leaves the user with nowhere to go, when the server has already said what is |
| 67 | // wrong through its diagnostics. |
| 68 | func (a *App) noCompletionsReason(path string) string { |
| 69 | if diagnostic, ok := a.language.FirstError(path); ok { |
| 70 | return "No completions — this file does not compile: " + diagnostic.Message |
| 71 | } |
| 72 | return "No completions here" |
| 73 | } |