|
1 |
| -import Gio from "gi://Gio"; |
| 1 | +import { setup } from "./python.js"; |
2 | 2 |
|
3 | 3 | import Document from "../../Document.js";
|
4 |
| -import { setup } from "./python.js"; |
| 4 | +import { applyTextEdits } from "../../lsp/sourceview.js"; |
5 | 5 |
|
6 | 6 | export class PythonDocument extends Document {
|
7 | 7 | constructor(...args) {
|
8 | 8 | super(...args);
|
9 | 9 |
|
10 |
| - /// XXX: We should await setup, but we can't in a Constructor. This would require bigger refactoring. |
11 | 10 | this.lspc = setup({ document: this });
|
12 | 11 | }
|
13 | 12 |
|
14 | 13 | async format() {
|
15 |
| - const code = await formatPythonCode(this.buffer.text); |
16 |
| - this.code_view.replaceText(code, true); |
| 14 | + // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_formatting |
| 15 | + const text_edits = await this.lspc.request("textDocument/formatting", { |
| 16 | + textDocument: { |
| 17 | + uri: this.file.get_uri(), |
| 18 | + }, |
| 19 | + options: { |
| 20 | + tabSize: 4, |
| 21 | + insertSpaces: true, |
| 22 | + trimTrailingWhitespace: true, |
| 23 | + insertFinalNewline: true, |
| 24 | + trimFinalNewlines: true, |
| 25 | + }, |
| 26 | + }); |
| 27 | + |
| 28 | + // lsp Ruff doesn't support diff - it just returns one edit |
| 29 | + // we don't want to loose the cursor position so we use this |
| 30 | + const state = this.code_view.saveState(); |
| 31 | + applyTextEdits(text_edits, this.buffer); |
| 32 | + await this.code_view.restoreState(state); |
17 | 33 | }
|
18 | 34 | }
|
19 |
| - |
20 |
| -function formatPythonCode(text) { |
21 |
| - const ruffLauncher = Gio.SubprocessLauncher.new( |
22 |
| - Gio.SubprocessFlags.STDIN_PIPE | |
23 |
| - Gio.SubprocessFlags.STDOUT_PIPE | |
24 |
| - Gio.SubprocessFlags.STDERR_PIPE, |
25 |
| - ); |
26 |
| - |
27 |
| - const ruffProcess = ruffLauncher.spawnv(["ruff", "format", "--quiet", "-"]); |
28 |
| - |
29 |
| - const [success, stdout, stderr] = ruffProcess.communicate_utf8(text, null); |
30 |
| - |
31 |
| - if (!success || stderr !== "") { |
32 |
| - console.error(`Error running ruff format: ${stderr}`); |
33 |
| - return text; |
34 |
| - } |
35 |
| - |
36 |
| - return stdout; |
37 |
| -} |
0 commit comments