diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index cd954a5..7f3af1f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -116,7 +116,7 @@ jobs:
- name: Install pytest for the host suite
run: python -m pip install --disable-pip-version-check pytest
- name: Verify Python highlighting, run configurations, and dependencies on Lithe 0.8.9
- run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(PinnedInterpreter)?|ManualRunAndDependencies)$'
+ run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride|PinnedInterpreter)?|ManualRunAndDependencies)$'
- name: Run the full Python host suite on the pinned desktop
env:
GOFLAGS: -tags=vivahead
diff --git a/README.md b/README.md
index 4da8c0c..6add6c9 100644
--- a/README.md
+++ b/README.md
@@ -31,20 +31,22 @@ Pyrefly 和 debugpy 随插件包分发,Python 解释器、pytest、uv、conda
## 设置
-**插件设置**(「语言与框架 › Python」,也在 设置 → 插件 → Python Support →「设置」),都立即生效:
+**插件设置**(「语言与框架 › Python」,也在 设置 → 插件 → Python Support →「设置」),除覆盖路径外都立即生效:
| 设置 | 默认 | 说明 |
| --- | --- | --- |
| 类型检查模式 | 默认 | Pyrefly 的预设:默认、自动、关闭、基础、宽松、严格、全部。项目有 `pyrefly.toml` 或 `[tool.pyrefly]` 时以项目配置为准;“自动”沿用附近的 mypy 或 Pyright 配置,没有时按“基础” |
-| 隐藏类型错误 | 关 | 所有文件都不显示类型错误,包括有自己 Pyrefly 配置的项目;悬停、跳转、补全照常。开启后类型检查模式选什么都不显示类型错误 |
+| 显示类型错误 | 始终开启 | 在哪些文件里显示类型错误:始终开启(没有 Pyrefly 配置的文件按类型检查模式)、仅已配置项目(只在 `pyrefly.toml` 或 `[tool.pyrefly]` 覆盖的文件里)、仅报告缺失导入、关闭(所有文件都不显示,包括有自己 Pyrefly 配置的项目)。Pyrefly 已经没有只报缺失导入的模式,所以“仅报告缺失导入”让没有 Pyrefly 配置的文件按“基础”检查:报告无法解析的导入和少数 Pyrefly 确定的错误。悬停、跳转、补全在各档都照常 |
| 诊断范围 | 仅打开的文件 | 或者“整个工作区”:没打开的文件也报告错误级别的问题 |
| 自动导入补全 | 开 | 补全列出还没导入的名字,确认时插入 `import` |
| 自动导入路径风格 | 绝对导入 | 插入导入时用完整模块路径还是包内相对路径。也用于“移动符号”“转换模块”代码操作;关闭自动导入补全后只有这两个操作用它 |
| 补全函数括号 | 关 | 补全函数或方法时加上 `()`,光标停在括号里 |
+| Python 解释器覆盖路径 | 空 | 填一个 Python 可执行文件后,构建任务、运行和 pytest 都用它,不再按下文的顺序查找;Pyrefly 分析和调试仍用查找到的解释器。修改后重新加载项目生效 |
## Python 解释器
-Pyrefly 分析代码、运行、测试、调试、读取依赖、安装依赖都用同一个解释器。Lithe 按这个顺序找:
+Pyrefly 分析代码、运行、测试、调试、读取依赖、安装依赖都用同一个解释器,除非设置了“Python 解释器覆盖路径”:那时构建任务、运行和
+pytest 用覆盖路径,Pyrefly 和调试仍用下面找到的解释器。Lithe 按这个顺序找:
1. **项目环境**:为项目固定的解释器;项目里的 `.venv`、`venv`、`.conda`(项目要先被信任);项目的 `.python-version` 和
`pyproject.toml` 的 `requires-python` 决定选哪个版本。
@@ -63,17 +65,17 @@ Python,固定也不行。受影响的有:
在此之前请把环境建在项目里:`python3 -m venv .venv` 或 `uv venv`;Poetry 先运行 `poetry config virtualenvs.in-project true`,
Pipenv 设置 `PIPENV_VENV_IN_PROJECT=1`。也可以固定 uv、pyenv、python.org 装的基础解释器,但那里没有环境里装的包。
-1.0.0 的“Python 解释器覆盖”设置在 1.1.0 删除了:它只管运行,Pyrefly 却用工具链里的解释器,两边可能不一致。原来填过的路径不再生效,请在工具链页固定它。
+项目外的环境暂时也可以填进“Python 解释器覆盖路径”,让运行和 pytest 先用上它。
## 设置预览
两块预览由插件后端按界面语言、外观和设置窗口宽度画出。它们用示例代码,不读取打开的项目;截图里的路径和版本是测试数据。
-**语言与框架 › Python**:顶部是当前用的 Python 解释器。下面四张卡片各对应一项设置:
+**语言与框架 › Python**:顶部是当前用的 Python 解释器;设置了覆盖路径时,下面多一行说明哪些流程改用它。下面四张卡片各对应一项设置:
| 卡片 | 画出什么 |
| --- | --- |
-| 类型检查模式 | 示例代码在所选预设下报告哪些错误;隐藏类型错误开启时标为“已隐藏” |
+| 类型检查模式 | 示例代码在所选预设下报告哪些错误;示例没有 Pyrefly 配置,“显示类型错误”不是始终开启时,卡片按它画出实际效果 |
| 诊断范围 | 一个小项目里哪些文件会被检查 |
| 自动导入补全 | 补全列出未导入的 `greet`,确认后按绝对或相对路径插入导入;关闭时只补全已导入的名字 |
| 补全函数括号 | 确认补全后是 `greet()` 还是 `greet` |
@@ -84,7 +86,7 @@ Pipenv 设置 `PIPENV_VENV_IN_PROJECT=1`。也可以固定 uv、pyenv、python.o
-**构建工具 › Python**:画出上面三步查找顺序,以及解释器用在哪些流程。这一页没有设置项,换解释器要到工具链页。
+**构建工具 › Python**:先画覆盖路径(有没有设置、设置后谁用它),再画上面三步查找顺序,以及查找到的解释器用在哪些流程。这一页没有设置项,换解释器要到工具链页。
@@ -165,7 +167,7 @@ export LITHE_TEST_PYTHON_PLUGIN_ARCHIVE="$PWD/dist/python-support-1.1.0-darwin-a
PYTEST_PYTHON=/path/to/python3.12 node scripts/e2e-host.mjs
# 用同一个包检查 0.8.9:高亮、当前文件运行、固定解释器、手动运行
PYTEST_PYTHON=/path/to/python3.12 node scripts/e2e-host.mjs --ref desktop-v0.8.9 \
- --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(PinnedInterpreter)?|ManualRunAndDependencies)$'
+ --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride|PinnedInterpreter)?|ManualRunAndDependencies)$'
```
插件包路径要写绝对路径。脚本把宿主检出到 `.artifacts/lithe-host`,复制 `e2e/host/desktop/` 下的测试后运行;`--source`、`--ref`、`--run`
diff --git a/backend/src/main.rs b/backend/src/main.rs
index 8d1cfdb..52d7712 100644
--- a/backend/src/main.rs
+++ b/backend/src/main.rs
@@ -4,6 +4,7 @@ mod discovery;
mod inspect;
mod pyrefly;
mod requirements;
+mod type_errors;
mod view;
use lithe_plugin_sdk::Backend;
diff --git a/backend/src/pyrefly.rs b/backend/src/pyrefly.rs
index e8441aa..8cecf90 100644
--- a/backend/src/pyrefly.rs
+++ b/backend/src/pyrefly.rs
@@ -1,5 +1,6 @@
//! Produces the packaged Pyrefly launch and its settings using the host's interpreter hint.
+use crate::type_errors::Display;
use lithe_plugin_sdk::{Context, FunctionError, PluginError};
use serde_json::{json, Value};
use std::collections::VecDeque;
@@ -31,10 +32,22 @@ impl LaunchResolver {
let settings = ¶ms["settings"];
let diagnostic_mode =
enum_setting(settings, "diagnosticMode", &["openFilesOnly", "workspace"]);
+ let preset = enum_setting(
+ settings,
+ "typeCheckingMode",
+ &["default", "auto", "off", "basic", "legacy", "strict", "all"],
+ );
+ let display = Display::parse(enum_setting(
+ settings,
+ "displayTypeErrors",
+ &Display::VALUES,
+ ))
+ .expect("a declared value parses");
+ let (preset, disabled) = display.pyrefly(preset);
let mut python = json!({
"pyrefly": {
- "typeCheckingMode": enum_setting(settings, "typeCheckingMode", &["default", "auto", "off", "basic", "legacy", "strict", "all"]),
- "disableTypeErrors": settings["disableTypeErrors"].as_bool().unwrap_or(false),
+ "typeCheckingMode": preset,
+ "disableTypeErrors": disabled,
"diagnosticMode": diagnostic_mode,
},
"analysis": {
diff --git a/backend/src/type_errors.rs b/backend/src/type_errors.rs
new file mode 100644
index 0000000..dc08d7f
--- /dev/null
+++ b/backend/src/type_errors.rs
@@ -0,0 +1,74 @@
+//! The `displayTypeErrors` setting, and the Pyrefly settings it stands for.
+//!
+//! Pyrefly 1.4.1, the version `vendor-lock.json` packages, deprecates
+//! `python.pyrefly.displayTypeErrors` for `typeCheckingMode` and
+//! `disableTypeErrors`, and the new settings win whenever both are sent. The
+//! plugin always sends `typeCheckingMode`, so passing the old value on would
+//! leave only `force-off` in effect. The plugin keeps its four choices and
+//! sends Pyrefly the pair that does what each choice's title says instead.
+
+/// Where type errors appear: the `displayTypeErrors` setting.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Display {
+ /// `force-on`: every file, files without a Pyrefly config by the preset.
+ AlwaysOn,
+ /// `default`: only files a `pyrefly.toml` or `[tool.pyrefly]` covers.
+ ConfiguredOnly,
+ /// `error-missing-imports`. Pyrefly 0.64 removed this mode, so files
+ /// without a Pyrefly config are checked with the `basic` preset, which
+ /// reports unresolved imports and a few errors Pyrefly is sure of.
+ MissingImports,
+ /// `force-off`: no file, whatever its own Pyrefly config says.
+ Off,
+}
+
+impl Display {
+ /// The declared option values, the default first.
+ pub const VALUES: [&'static str; 4] =
+ ["force-on", "default", "error-missing-imports", "force-off"];
+
+ pub fn parse(value: &str) -> Option {
+ Some(match value {
+ "force-on" => Display::AlwaysOn,
+ "default" => Display::ConfiguredOnly,
+ "error-missing-imports" => Display::MissingImports,
+ "force-off" => Display::Off,
+ _ => return None,
+ })
+ }
+
+ /// The `typeCheckingMode` and `disableTypeErrors` Pyrefly gets, where
+ /// `preset` is the `typeCheckingMode` setting. A preset reaches only the
+ /// files no Pyrefly config covers; a configured project keeps its own.
+ pub fn pyrefly(self, preset: &str) -> (&str, bool) {
+ match self {
+ Display::AlwaysOn => (preset, false),
+ Display::ConfiguredOnly => ("off", false),
+ Display::MissingImports => ("basic", false),
+ Display::Off => (preset, true),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_declared_value_parses_and_nothing_else_does() {
+ for value in Display::VALUES {
+ assert!(Display::parse(value).is_some(), "{value}");
+ }
+ for value in ["", "on", "Force-On", "disable"] {
+ assert_eq!(Display::parse(value), None, "{value}");
+ }
+ }
+
+ #[test]
+ fn each_choice_sends_the_settings_that_do_what_its_title_says() {
+ assert_eq!(Display::AlwaysOn.pyrefly("strict"), ("strict", false));
+ assert_eq!(Display::ConfiguredOnly.pyrefly("strict"), ("off", false));
+ assert_eq!(Display::MissingImports.pyrefly("strict"), ("basic", false));
+ assert_eq!(Display::Off.pyrefly("strict"), ("strict", true));
+ }
+}
diff --git a/backend/src/view/language.rs b/backend/src/view/language.rs
index 5bfeed5..c343e64 100644
--- a/backend/src/view/language.rs
+++ b/backend/src/view/language.rs
@@ -17,7 +17,7 @@ use super::scene::{
code, column, group, pair, path, pill, rect, runs, squiggle, text, text_width, token, Node,
CAPTION, STRONG,
};
-use super::settings::{ImportFormat, Mode, Scope, Settings};
+use super::settings::{Display, ImportFormat, Mode, Scope, Settings};
use super::words::Words;
use serde_json::{json, Value};
@@ -32,7 +32,7 @@ pub const TOOLS: [&str; 1] = ["python"];
/// The settings the cards show; a draft of any of them marks the preview.
pub const SETTINGS: [&str; 6] = [
"typeCheckingMode",
- "disableTypeErrors",
+ "displayTypeErrors",
"diagnosticMode",
"autoImportCompletions",
"importFormat",
@@ -139,12 +139,21 @@ struct Card<'a> {
preview: Vec,
}
-/// The region's nodes: the interpreter row, then the preview.
+/// The region's nodes: the interpreter row, then the preview. While the
+/// override path is set, a banner under the row says which commands use it
+/// instead.
pub fn view(settings: &Settings, words: &Words, width: Option) -> Vec {
- let tools: Vec = TOOLS
+ let mut tools: Vec = TOOLS
.iter()
.map(|tool| json!({ "type": "tool", "tool": tool }))
.collect();
+ if let Some(path) = &settings.interpreter_override {
+ tools.push(json!({
+ "type": "banner",
+ "text": (words.override_banner)(path),
+ "tone": "accent",
+ }));
+ }
vec![
json!({
"type": "section",
@@ -174,15 +183,20 @@ fn mode_index(mode: Mode) -> usize {
/// order the cards stand.
fn values<'a>(settings: &Settings, words: &'a Words) -> [(&'a str, bool, &'a str); 4] {
let switch = |on: bool| if on { words.on } else { words.off };
- let mode = if settings.hide_type_errors {
- (words.hidden, false, words.hidden_note)
- } else {
- let index = mode_index(settings.mode);
- (
- words.modes[index],
- settings.mode != Mode::Off,
- words.mode_notes[index],
- )
+ let display =
+ |index: usize, lit: bool| (words.displays[index], lit, words.display_notes[index]);
+ let mode = match settings.display {
+ Display::AlwaysOn => {
+ let index = mode_index(settings.mode);
+ (
+ words.modes[index],
+ settings.mode != Mode::Off,
+ words.mode_notes[index],
+ )
+ }
+ Display::ConfiguredOnly => display(0, false),
+ Display::MissingImports => display(1, true),
+ Display::Off => display(2, false),
};
let scope = match settings.scope {
Scope::OpenFiles => (words.scope_open, false, words.scope_open_note),
@@ -235,7 +249,10 @@ pub fn canvas(settings: &Settings, words: &Words, width: Option) -> Value {
value: mode.0,
lit: mode.1,
note: mode.2,
- changed: settings.any_changed(&["typeCheckingMode", "disableTypeErrors"]),
+ // The preset decides this card only while type errors are always on.
+ changed: settings.is_changed("displayTypeErrors")
+ || (settings.display == Display::AlwaysOn
+ && settings.is_changed("typeCheckingMode")),
preview: type_check_preview(settings.reporting(), words, box_w),
},
Card {
@@ -435,7 +452,7 @@ fn reported(mode: Mode) -> (usize, Option) {
/// A function missing an annotation, a call with a string for a float, and a
/// misspelled name, in a box `box_w` wide; under it what the preset in force
-/// reports. Nothing is reported while type errors are hidden or off.
+/// reports. Nothing is reported while the preset is off or type errors are.
fn type_check_preview(reporting: Option, words: &Words, box_w: f64) -> Vec {
let mut nodes = numbered(vec![
vec![
@@ -708,7 +725,7 @@ mod tests {
let mut pairs: Vec<(&str, &str)> = w
.modes
.iter()
- .chain([&w.hidden])
+ .chain(&w.displays)
.map(|value| (w.mode_title, *value))
.collect();
pairs.extend([w.scope_open, w.scope_workspace].map(|value| (w.scope_title, value)));
@@ -734,8 +751,7 @@ mod tests {
fn every_note_fits_the_narrowest_card() {
for language in ["en", "zh-Hans"] {
let w = words::for_language(language);
- let notes = w.mode_notes.iter().copied().chain([
- w.hidden_note,
+ let notes = w.mode_notes.iter().chain(&w.display_notes).copied().chain([
w.scope_open_note,
w.scope_workspace_note,
w.import_absolute_note,
diff --git a/backend/src/view/mod.rs b/backend/src/view/mod.rs
index 428048e..9e02fdd 100644
--- a/backend/src/view/mod.rs
+++ b/backend/src/view/mod.rs
@@ -70,13 +70,14 @@ fn render(event: &ViewEvent) -> Result<(Vec, u64), PluginError> {
let nodes = language::view(&settings, words, event.width);
Ok((nodes, settings.unrecognized))
}
- PYTHON_REGION => Ok((
- vec![
+ PYTHON_REGION => {
+ let settings = Settings::read(event);
+ let nodes = vec![
json!({ "type": "tool", "tool": PYTHON_TOOL }),
- resolution::canvas(words, event.width),
- ],
- 0,
- )),
+ resolution::canvas(words, settings.interpreter_override.as_deref(), event.width),
+ ];
+ Ok((nodes, settings.unrecognized))
+ }
_ => Err(unknown_region()),
}
}
@@ -253,9 +254,15 @@ mod tests {
for mode in MODES {
cases.push((json!({ "typeCheckingMode": mode }), json!({})));
}
+ for display in ["default", "error-missing-imports", "force-off"] {
+ cases.push((
+ json!({ "typeCheckingMode": "all", "displayTypeErrors": "force-on" }),
+ json!({ "displayTypeErrors": display }),
+ ));
+ }
cases.push((
- json!({ "typeCheckingMode": "all", "disableTypeErrors": false }),
- json!({ "disableTypeErrors": true }),
+ json!({ "pythonExecutable": "/opt/homebrew/opt/python@3.13/libexec/bin/python3" }),
+ json!({}),
));
for (scope, auto_import, format, parens) in [
("workspace", true, "relative", true),
@@ -638,20 +645,76 @@ mod tests {
}
#[test]
- fn off_and_hidden_type_errors_report_nothing() {
+ fn the_off_preset_and_hidden_type_errors_report_nothing() {
let (squiggles, shown) = reported(json!({ "typeCheckingMode": "off" }), json!({}));
assert_eq!(squiggles, 0);
assert!(
shown.contains("No type errors") && !shown.contains(" · "),
"{shown}"
);
+ for (display, pill, note) in [
+ ("default", "Configured only", "has no Pyrefly config"),
+ ("force-off", "Off", "Display type errors is Off"),
+ ] {
+ let (squiggles, shown) = reported(
+ json!({ "typeCheckingMode": "all", "displayTypeErrors": display }),
+ json!({}),
+ );
+ assert_eq!(squiggles, 0, "{display}");
+ assert!(shown.contains(pill) && shown.contains(note), "{shown}");
+ assert!(!shown.contains("no-any-return-implicit"), "{shown}");
+ }
+ }
+
+ #[test]
+ fn missing_imports_only_checks_the_sample_as_basic_whatever_the_preset() {
let (squiggles, shown) = reported(
- json!({ "typeCheckingMode": "all", "disableTypeErrors": true }),
+ json!({ "typeCheckingMode": "all", "displayTypeErrors": "error-missing-imports" }),
json!({}),
);
- assert_eq!(squiggles, 0);
- assert!(shown.contains("Hidden") && shown.contains("Hide type errors is on"));
- assert!(!shown.contains("no-any-return-implicit"));
+ assert_eq!(squiggles, 1);
+ assert!(shown.contains("unknown-name · 1 error"), "{shown}");
+ assert!(shown.contains("Missing imports") && shown.contains("checks as Basic"));
+ }
+
+ #[test]
+ fn the_override_path_shows_under_the_interpreter_row_and_in_the_lookup() {
+ let path = "/opt/homebrew/opt/python@3.13/libexec/bin/python3";
+ let language = nodes(
+ LANGUAGE_REGION,
+ "en",
+ json!({ "pythonExecutable": path }),
+ json!({}),
+ );
+ let rows = language[0]["children"].as_array().unwrap();
+ assert_eq!(rows.len(), 2);
+ assert_eq!(rows[1]["type"], "banner");
+ assert!(rows[1]["text"].as_str().unwrap().contains(path));
+ // No banner while the path is empty.
+ let unset = nodes(LANGUAGE_REGION, "en", json!({}), json!({}));
+ assert_eq!(unset[0]["children"].as_array().unwrap().len(), 1);
+
+ // The path keeps its end in the narrowest scene.
+ let set = words_of(&nodes(
+ PYTHON_REGION,
+ "en",
+ json!({ "pythonExecutable": path }),
+ json!({}),
+ ));
+ assert!(
+ set.contains("Python executable override") && set.contains("/libexec/bin/python3"),
+ "{set}"
+ );
+ assert!(set.contains("Build, run and pytest use it"));
+ assert!(
+ set.contains("Used to\nanalyze\ndebug") && !set.contains("\nrun\n"),
+ "{set}"
+ );
+ let empty = words_of(&nodes(PYTHON_REGION, "zh-Hans", json!({}), json!({})));
+ assert!(
+ empty.contains("未设置") && empty.contains("语言服务\n运行\n测试\n调试\n安装依赖"),
+ "{empty}"
+ );
}
#[test]
@@ -747,21 +810,23 @@ mod tests {
LANGUAGE_REGION,
"zh-Hans",
json!({}),
- json!({ "disableTypeErrors": true }),
+ json!({ "displayTypeErrors": "force-off" }),
));
- assert!(chinese.contains("含未应用的修改") && chinese.contains("已隐藏"));
+ assert!(chinese.contains("含未应用的修改") && chinese.contains("「显示类型错误」已关闭"));
}
#[test]
fn the_python_diagram_lists_the_lookup_in_order_then_pyrefly() {
let shown = words_of(&nodes(PYTHON_REGION, "en", json!({}), json!({})));
let order: Vec = [
+ "Python executable override",
+ "Not set",
"Tried first",
".venv, venv, .conda",
"Global default",
"Tried last",
"VIRTUAL_ENV",
- "Pyrefly uses the same interpreter",
+ "Pyrefly uses the interpreter found",
]
.iter()
.map(|word| {
diff --git a/backend/src/view/resolution.rs b/backend/src/view/resolution.rs
index 1dc7837..93c09ec 100644
--- a/backend/src/view/resolution.rs
+++ b/backend/src/view/resolution.rs
@@ -4,8 +4,11 @@
//! The steps follow `toolDefinitions[python].invocation.executables` in
//! `plugin.json`: what the Toolchains page sets for the project and the
//! environments in it, then what it sets for every project, then the
-//! automatic lookup. The view sees the plugin's settings only, not the
-//! Toolchains page, so it shows the order; the toolchain row above it shows
+//! automatic lookup. Above them stands the `pythonExecutable` override,
+//! which `buildSystems[python].invocation.executables` tries before the
+//! lookup, so it decides build, run and pytest but not Pyrefly or debugging.
+//! The view sees the plugin's settings only, not the Toolchains page, so it
+//! shows the order and the override path; the toolchain row above it shows
//! the interpreter found.
//!
//! The region sits in the build system page's detail pane, 344 points wide
@@ -36,8 +39,10 @@ const STEP_GAP: f64 = 10.0;
const TITLE_MIDDLE: f64 = 17.0;
/// The left edge of a step's lines, and their room on its right.
const LINE_X: f64 = 12.0;
+/// The top of the first step, under the override card.
+const STEPS_Y: f64 = HEADER + STEP_H + STEP_GAP;
/// The top of the Pyrefly card, after the three steps.
-const PYREFLY_Y: f64 = HEADER + 3.0 * (STEP_H + STEP_GAP);
+const PYREFLY_Y: f64 = STEPS_Y + 3.0 * (STEP_H + STEP_GAP);
/// The top of the row of what the interpreter is used for.
const USES_Y: f64 = PYREFLY_Y + STEP_H + 14.0;
pub const HEIGHT: f64 = USES_Y + 22.0;
@@ -51,9 +56,10 @@ struct Step<'a> {
}
/// The diagram for a view `width` points wide, or for the smallest settings
-/// window when the host reports no width. A host that reports it sends
-/// `resize` with the new width, and the scene is drawn again for it.
-pub fn canvas(words: &Words, width: Option) -> Value {
+/// window when the host reports no width, with the override path when it is
+/// set. A host that reports the width sends `resize` with the new width, and
+/// the scene is drawn again for it.
+pub fn canvas(words: &Words, override_path: Option<&str>, width: Option) -> Value {
let scene_w = width.unwrap_or(DEFAULT_WIDTH).max(MIN_WIDTH);
let step_w = scene_w - STEP_X;
let steps = [
@@ -77,9 +83,12 @@ pub fn canvas(words: &Words, width: Option) -> Value {
},
];
- let mut nodes = vec![text(0.0, 17.0, words.resolution_title, "strong")];
+ let mut nodes = vec![
+ text(0.0, 17.0, words.resolution_title, "strong"),
+ override_card(words, override_path, step_w),
+ ];
for (index, step) in steps.iter().enumerate() {
- let y = HEADER + index as f64 * (STEP_H + STEP_GAP);
+ let y = STEPS_Y + index as f64 * (STEP_H + STEP_GAP);
if index > 0 {
// The rail joins the dots.
let above = y - STEP_GAP - STEP_H + TITLE_MIDDLE + DOT / 2.0 + 4.0;
@@ -93,7 +102,7 @@ pub fn canvas(words: &Words, width: Option) -> Value {
nodes.push(draw(y, index + 1, step, step_w));
}
nodes.push(pyrefly(words, step_w));
- nodes.extend(uses(words).0);
+ nodes.extend(uses(words, override_path.is_some()).0);
let mut canvas = json!({
"type": "canvas",
"id": CANVAS_ID,
@@ -144,8 +153,60 @@ fn draw(y: f64, number: usize, step: &Step, step_w: f64) -> Node {
)
}
-/// A card's two lines of detail, in a card `card_w` wide.
-fn lines(lines: &[&str; 2], card_w: f64) -> Vec {
+/// The override path, off the rail above the lookup: dashed while empty, and
+/// framed like the first step with the path while set, since build, run and
+/// pytest then take it before any step.
+fn override_card(words: &Words, path: Option<&str>, step_w: f64) -> Node {
+ let (chip, fill, ink) = match path {
+ Some(_) => (words.override_set, token("$selection"), token("$text")),
+ None => (
+ words.override_unset,
+ token("$badge"),
+ token("$textSecondary"),
+ ),
+ };
+ let (_, chip_w) = pill(0.0, 0.0, chip, fill.clone(), ink.clone());
+ let chip_x = step_w - 10.0 - chip_w;
+ let frame = rect(0.0, 0.0, step_w, STEP_H).radius(8.0);
+ let frame = match path {
+ Some(_) => frame.fill(token("$surface")).stroke(token("$line"), 1.0),
+ None => frame.stroke(token("$line"), 1.0).dash(&[4.0, 3.0]),
+ };
+ let mut card = vec![
+ frame,
+ text(LINE_X, TITLE_MIDDLE + 4.5, words.override_title, "strong")
+ .max_width(chip_x - LINE_X - 10.0),
+ pill(chip_x, TITLE_MIDDLE - 10.0, chip, fill, ink).0,
+ ];
+ match path {
+ Some(path) => {
+ card.push(
+ text(LINE_X, 40.0, &tail(path, step_w - 2.0 * LINE_X), "caption")
+ .color(token("$text"))
+ .max_width(step_w - 2.0 * LINE_X),
+ );
+ card.extend(lines(&["", words.override_set_detail], step_w).pop());
+ }
+ None => card.extend(lines(&words.override_unset_detail, step_w)),
+ }
+ group(STEP_X, HEADER, card)
+}
+
+/// The end of `path` that fits `room`, after an ellipsis when it is cut:
+/// the interpreter's name and its environment are at the end.
+fn tail(path: &str, room: f64) -> String {
+ if text_width(path, CAPTION) <= room {
+ return path.to_string();
+ }
+ let chars: Vec = path.chars().collect();
+ (1..chars.len())
+ .map(|start| format!("…{}", chars[start..].iter().collect::()))
+ .find(|cut| text_width(cut, CAPTION) <= room)
+ .unwrap_or_else(|| "…".into())
+}
+
+/// A card's lines of detail, at most two, in a card `card_w` wide.
+fn lines(lines: &[&str], card_w: f64) -> Vec {
lines
.iter()
.zip([40.0, 55.0])
@@ -199,14 +260,18 @@ fn pyrefly(words: &Words, step_w: f64) -> Node {
)
}
-/// What Lithe uses the interpreter for, after the cards, and where the row
-/// ends.
-fn uses(words: &Words) -> (Vec, f64) {
+/// What Lithe uses the interpreter the lookup finds for, after the cards, and
+/// where the row ends. While the override path is set, it takes run, test
+/// and install.
+fn uses(words: &Words, overridden: bool) -> (Vec, f64) {
let mut nodes =
vec![text(0.0, USES_Y + 14.0, words.used_for, "caption").color(token("$textMuted"))];
let mut x = text_width(words.used_for, CAPTION) + 8.0;
let mut end = x;
- for word in words.uses {
+ for (index, word) in words.uses.iter().enumerate() {
+ if overridden && [1, 2, 4].contains(&index) {
+ continue;
+ }
let (chip, width) = pill(x, USES_Y, word, token("$badge"), token("$textSecondary"));
nodes.push(chip);
end = x + width;
@@ -221,11 +286,26 @@ mod tests {
use crate::view::scene::STRONG;
use crate::view::words;
+ #[test]
+ fn a_long_override_path_keeps_its_end() {
+ let path =
+ "/Users/someone/projects/a-very-long-project-name/.venv-with-a-long-name/bin/python3";
+ let cut = tail(path, 200.0);
+ assert!(
+ cut.starts_with('…') && cut.ends_with("/bin/python3"),
+ "{cut}"
+ );
+ assert!(text_width(&cut, CAPTION) <= 200.0);
+ assert_eq!(tail("/usr/bin/python3", 200.0), "/usr/bin/python3");
+ }
+
#[test]
fn the_row_of_uses_fits_the_narrowest_scene_in_both_languages() {
for language in ["en", "zh-Hans"] {
- let (_, end) = uses(words::for_language(language));
- assert!(end <= MIN_WIDTH, "{language}: {end}");
+ for overridden in [false, true] {
+ let (_, end) = uses(words::for_language(language), overridden);
+ assert!(end <= MIN_WIDTH, "{language}: {end}");
+ }
}
}
@@ -239,6 +319,8 @@ mod tests {
w.step_global_detail,
w.step_automatic_detail,
w.pyrefly_detail,
+ w.override_unset_detail,
+ [w.override_set_detail; 2],
]
.concat()
{
@@ -247,6 +329,18 @@ mod tests {
}
let width = text_width(w.pyrefly_title, STRONG);
assert!(width <= room, "{language}: {} ({width})", w.pyrefly_title);
+ // The override title keeps its room beside the wider chip.
+ let chip = [w.override_set, w.override_unset]
+ .map(|chip| text_width(chip, CAPTION) + 16.0)
+ .into_iter()
+ .fold(0.0, f64::max);
+ let width = text_width(w.override_title, STRONG);
+ let room = MIN_WIDTH - STEP_X - 10.0 - chip - LINE_X - 10.0;
+ assert!(
+ width <= room,
+ "{language}: {} ({width} of {room})",
+ w.override_title
+ );
let width = text_width(w.resolution_title, STRONG);
assert!(
width <= MIN_WIDTH,
diff --git a/backend/src/view/settings.rs b/backend/src/view/settings.rs
index 16f25de..b687c38 100644
--- a/backend/src/view/settings.rs
+++ b/backend/src/view/settings.rs
@@ -4,6 +4,7 @@
//! user changed but has not applied (the draft) wins over the saved one, and a
//! setting with neither shows the default `plugin.json` declares.
+pub use crate::type_errors::Display;
use lithe_plugin_sdk::view::ViewEvent;
use serde_json::Value;
@@ -82,10 +83,12 @@ impl ImportFormat {
/// The plugin's settings as the settings window holds them now.
#[derive(Debug)]
pub struct Settings {
+ /// The Python executable override: the interpreter build, run and
+ /// pytest commands use instead of the Toolchains page's, when set.
+ pub interpreter_override: Option,
pub mode: Mode,
- /// Pyrefly's `disableTypeErrors`: no file shows type errors, whatever
- /// the preset or the project's own Pyrefly config says.
- pub hide_type_errors: bool,
+ /// Where type errors appear, which decides whether the preset does.
+ pub display: Display,
pub scope: Scope,
pub auto_import: bool,
pub import_format: ImportFormat,
@@ -104,10 +107,17 @@ impl Settings {
changed: Vec::new(),
unrecognized: 0,
};
+ let interpreter_override = reader.read("pythonExecutable", Value::from(""), |value| {
+ value
+ .as_str()
+ .map(|path| (!path.is_empty()).then(|| path.to_owned()))
+ });
let mode = reader.read("typeCheckingMode", Value::from("default"), |value| {
value.as_str().and_then(Mode::parse)
});
- let hide_type_errors = reader.boolean("disableTypeErrors", false);
+ let display = reader.read("displayTypeErrors", Value::from("force-on"), |value| {
+ value.as_str().and_then(Display::parse)
+ });
let scope = reader.read("diagnosticMode", Value::from("openFilesOnly"), |value| {
value.as_str().and_then(Scope::parse)
});
@@ -117,8 +127,9 @@ impl Settings {
});
let function_parens = reader.boolean("completeFunctionParens", false);
Self {
+ interpreter_override,
mode,
- hide_type_errors,
+ display,
scope,
auto_import,
import_format,
@@ -128,10 +139,16 @@ impl Settings {
}
}
- /// The preset that decides what the sample reports: none while type
- /// errors are hidden, which silences every preset.
+ /// The preset that decides what the sample, which has no Pyrefly config,
+ /// reports: the one `displayTypeErrors` sends Pyrefly for such a file,
+ /// or none when that is `off` or type errors are switched off.
pub fn reporting(&self) -> Option {
- (!self.hide_type_errors).then(|| self.mode.applied())
+ match self.display {
+ Display::AlwaysOn => Some(self.mode.applied()),
+ Display::ConfiguredOnly => Some(Mode::Off),
+ Display::MissingImports => Some(Mode::Basic),
+ Display::Off => None,
+ }
}
/// Whether the user changed `id` without applying it yet.
@@ -197,53 +214,64 @@ mod tests {
#[test]
fn a_setting_without_a_value_shows_its_declared_default() {
let settings = Settings::read(&event(json!({}), json!({})));
+ assert_eq!(settings.interpreter_override, None);
assert_eq!(settings.mode, Mode::Default);
- assert!(!settings.hide_type_errors);
+ assert_eq!(settings.display, Display::AlwaysOn);
assert_eq!(settings.scope, Scope::OpenFiles);
assert!(settings.auto_import && !settings.function_parens);
assert_eq!(settings.import_format, ImportFormat::Absolute);
assert_eq!(settings.unrecognized, 0);
- assert!(!settings.any_changed(&["typeCheckingMode", "disableTypeErrors", "importFormat"]));
+ assert!(!settings.any_changed(&["typeCheckingMode", "displayTypeErrors", "importFormat"]));
}
#[test]
fn the_draft_wins_over_the_saved_value_and_counts_as_a_change() {
let settings = Settings::read(&event(
- json!({ "typeCheckingMode": "basic", "importFormat": "absolute", "disableTypeErrors": false }),
- json!({ "typeCheckingMode": "strict", "disableTypeErrors": false, "importFormat": "relative" }),
+ json!({ "typeCheckingMode": "basic", "importFormat": "absolute", "displayTypeErrors": "default" }),
+ json!({ "typeCheckingMode": "strict", "displayTypeErrors": "default", "importFormat": "relative", "pythonExecutable": "/opt/py/bin/python3" }),
));
assert_eq!(settings.mode, Mode::Strict);
assert_eq!(settings.import_format, ImportFormat::Relative);
+ assert_eq!(
+ settings.interpreter_override.as_deref(),
+ Some("/opt/py/bin/python3")
+ );
assert!(settings.is_changed("typeCheckingMode"));
assert!(settings.is_changed("importFormat"));
+ assert!(settings.is_changed("pythonExecutable"));
// A draft equal to the value in force changes nothing.
- assert!(!settings.is_changed("disableTypeErrors"));
+ assert!(!settings.is_changed("displayTypeErrors"));
assert!(!settings.is_changed("diagnosticMode"));
}
#[test]
fn a_value_outside_the_declaration_shows_the_default_and_is_counted() {
let settings = Settings::read(&event(
- json!({ "typeCheckingMode": "pedantic", "autoImportCompletions": "yes" }),
- // The removed setting the kill switch replaced is not read at all.
- json!({ "displayTypeErrors": "force-off" }),
+ json!({ "typeCheckingMode": "pedantic", "autoImportCompletions": "yes", "pythonExecutable": 3 }),
+ json!({ "displayTypeErrors": "hidden" }),
));
assert_eq!(settings.mode, Mode::Default);
- assert!(settings.auto_import && !settings.hide_type_errors);
- assert_eq!(settings.unrecognized, 2);
+ assert_eq!(settings.display, Display::AlwaysOn);
+ assert_eq!(settings.interpreter_override, None);
+ assert!(settings.auto_import);
+ assert_eq!(settings.unrecognized, 4);
}
#[test]
- fn automatic_checks_the_unconfigured_sample_as_basic_and_hidden_errors_report_nothing() {
- let read = |mode: &str, hide: bool| {
+ fn the_unconfigured_sample_reports_by_the_preset_pyrefly_gets_for_it() {
+ let read = |mode: &str, display: &str| {
Settings::read(&event(
- json!({ "typeCheckingMode": mode, "disableTypeErrors": hide }),
+ json!({ "typeCheckingMode": mode, "displayTypeErrors": display }),
json!({}),
))
.reporting()
};
- assert_eq!(read("auto", false), Some(Mode::Basic));
- assert_eq!(read("legacy", false), Some(Mode::Legacy));
- assert_eq!(read("strict", true), None);
+ assert_eq!(read("auto", "force-on"), Some(Mode::Basic));
+ assert_eq!(read("legacy", "force-on"), Some(Mode::Legacy));
+ // Configured projects only silences a file without a Pyrefly config.
+ assert_eq!(read("strict", "default"), Some(Mode::Off));
+ // Pyrefly has no missing-imports-only mode any more: Basic stands in.
+ assert_eq!(read("all", "error-missing-imports"), Some(Mode::Basic));
+ assert_eq!(read("strict", "force-off"), None);
}
}
diff --git a/backend/src/view/words.rs b/backend/src/view/words.rs
index 78e725d..c1c273f 100644
--- a/backend/src/view/words.rs
+++ b/backend/src/view/words.rs
@@ -17,15 +17,20 @@ pub struct Words {
pub interpreter_title: &'static str,
pub interpreter_info: &'static str,
+ /// The banner under the interpreter row while the override path is set.
+ pub override_banner: fn(&str) -> String,
pub mode_title: &'static str,
/// The pill of each preset, in the order of `Mode`: automatic, off,
/// basic, legacy, default, strict, all.
pub modes: [&'static str; 7],
pub mode_notes: [&'static str; 7],
- /// The pill and the note while the kill switch hides every type error.
- pub hidden: &'static str,
- pub hidden_note: &'static str,
+ /// The pill and the note of the type checking card for each
+ /// `displayTypeErrors` choice that overrides the preset, in the order of
+ /// `Display`: configured projects only, missing imports only, off. Always
+ /// on shows the preset's own.
+ pub displays: [&'static str; 3],
+ pub display_notes: [&'static str; 3],
/// How many errors the sample reports, after the error code shown.
pub errors: fn(usize) -> String,
@@ -57,6 +62,14 @@ pub struct Words {
pub resolution_title: &'static str,
pub resolution_label: &'static str,
+ /// The card for the override path above the lookup: its title, the chip
+ /// while it is set and while it is empty, and its lines while empty and
+ /// the second line while set, under the path.
+ pub override_title: &'static str,
+ pub override_set: &'static str,
+ pub override_unset: &'static str,
+ pub override_unset_detail: [&'static str; 2],
+ pub override_set_detail: &'static str,
pub step_project: &'static str,
pub step_project_detail: [&'static str; 2],
pub step_global: &'static str,
@@ -69,9 +82,19 @@ pub struct Words {
pub then: &'static str,
pub last: &'static str,
pub used_for: &'static str,
+ /// What the interpreter the lookup finds is used for: analyze, run,
+ /// test, debug, install. The override path takes run, test and install.
pub uses: [&'static str; 5],
}
+fn override_banner_zh(path: &str) -> String {
+ format!("已设置「Python 解释器覆盖路径」:构建、运行和 pytest 使用 {path};Pyrefly 分析和调试仍用上面的解释器。")
+}
+
+fn override_banner_en(path: &str) -> String {
+ format!("Python executable override is set: build, run and pytest use {path}; Pyrefly analysis and debugging still use the interpreter above.")
+}
+
fn errors_zh(count: usize) -> String {
format!("共 {count} 个错误")
}
@@ -92,7 +115,8 @@ const ZH: Words = Words {
off: "关",
interpreter_title: "Python 解释器",
- interpreter_info: "Pyrefly 分析代码、运行、测试和安装依赖都用这个解释器,Pyrefly 从它的 site-packages 解析第三方库。点击这一行,到「工具链」页为项目或全局选择 .venv、uv、conda、pyenv 等环境,或添加其他目录。",
+ interpreter_info: "Pyrefly 分析代码和调试用这个解释器,Pyrefly 从它的 site-packages 解析第三方库;没有设置「Python 解释器覆盖路径」时,构建、运行、pytest 和安装依赖也用它。点击这一行,到「工具链」页为项目或全局选择 .venv、uv、conda、pyenv 等环境,或添加其他目录。",
+ override_banner: override_banner_zh,
mode_title: "类型检查模式",
modes: ["自动", "关闭", "基础", "宽松", "默认", "严格", "全部"],
@@ -105,8 +129,12 @@ const ZH: Words = Words {
"另外要求参数注解等",
"所有检查都按错误报告",
],
- hidden: "已隐藏",
- hidden_note: "「隐藏类型错误」已开启,所有文件都不显示",
+ displays: ["仅已配置项目", "仅报告缺失导入", "关闭"],
+ display_notes: [
+ "示例没有 Pyrefly 配置,不显示类型错误",
+ "Pyrefly 已无此模式,未配置的文件按基础检查",
+ "「显示类型错误」已关闭,所有文件都不显示",
+ ],
errors: errors_zh,
scope_title: "诊断范围",
@@ -135,6 +163,14 @@ const ZH: Words = Words {
resolution_title: "Lithe 按这个顺序找 Python 解释器",
resolution_label: "Lithe 查找 Python 解释器的顺序",
+ override_title: "Python 解释器覆盖路径",
+ override_set: "已设置",
+ override_unset: "未设置",
+ override_unset_detail: [
+ "留空时,构建、运行和 pytest 也按下面查找",
+ "在「语言与框架 › Python」设置",
+ ],
+ override_set_detail: "构建、运行和 pytest 用它,不按下面查找",
step_project: "项目环境",
step_project_detail: [
"为项目固定的解释器 → .venv、venv、.conda",
@@ -150,7 +186,7 @@ const ZH: Words = Words {
"VIRTUAL_ENV → PATH 中的 python3、python",
"→ uv、pyenv、conda、python.org 的安装",
],
- pyrefly_title: "Pyrefly 用同一个解释器",
+ pyrefly_title: "Pyrefly 用查找到的解释器",
pyrefly_detail: [
"从它的 site-packages 解析第三方库",
"换解释器后,缺失导入的报错随之更新",
@@ -171,7 +207,8 @@ const EN: Words = Words {
off: "Off",
interpreter_title: "Python interpreter",
- interpreter_info: "Pyrefly analyzes the code with this interpreter, and Lithe runs, tests and installs packages with it; Pyrefly resolves third-party imports from its site-packages. Choose the row to pick a .venv, uv, conda or pyenv environment, or another directory, for the project or for all projects on the Toolchains page.",
+ interpreter_info: "Pyrefly analyzes the code and Lithe debugs with this interpreter; Pyrefly resolves third-party imports from its site-packages. Unless Python executable override is set, Lithe also builds, runs, tests and installs packages with it. Choose the row to pick a .venv, uv, conda or pyenv environment, or another directory, for the project or for all projects on the Toolchains page.",
+ override_banner: override_banner_en,
mode_title: "Type checking mode",
modes: ["Automatic", "Off", "Basic", "Legacy", "Default", "Strict", "All"],
@@ -184,8 +221,12 @@ const EN: Words = Words {
"Also asks for parameter annotations",
"Every check, reported as an error",
],
- hidden: "Hidden",
- hidden_note: "Hide type errors is on: no file shows them",
+ displays: ["Configured only", "Missing imports", "Off"],
+ display_notes: [
+ "The sample has no Pyrefly config: none shown",
+ "No such mode in Pyrefly now: checks as Basic",
+ "Display type errors is Off: no file shows them",
+ ],
errors: errors_en,
scope_title: "Diagnostic scope",
@@ -214,6 +255,14 @@ const EN: Words = Words {
resolution_title: "How Lithe finds the Python interpreter",
resolution_label: "The order in which Lithe looks for the Python interpreter",
+ override_title: "Python executable override",
+ override_set: "Set",
+ override_unset: "Not set",
+ override_unset_detail: [
+ "When empty, build, run and pytest use the lookup",
+ "Set in Languages & Frameworks › Python",
+ ],
+ override_set_detail: "Build, run and pytest use it, not the lookup",
step_project: "Project",
step_project_detail: [
"Pinned for the project → .venv, venv, .conda",
@@ -229,7 +278,7 @@ const EN: Words = Words {
"VIRTUAL_ENV → python3, python on PATH",
"→ uv, pyenv, conda and python.org installs",
],
- pyrefly_title: "Pyrefly uses the same interpreter",
+ pyrefly_title: "Pyrefly uses the interpreter found",
pyrefly_detail: [
"It resolves third-party imports from its",
"site-packages, so switching updates them",
@@ -265,6 +314,12 @@ mod tests {
}
}
+ #[test]
+ fn the_override_banner_names_the_path_in_each_language() {
+ assert!((EN.override_banner)("/opt/py/bin/python3").contains("use /opt/py/bin/python3;"));
+ assert!((ZH.override_banner)("/opt/py/bin/python3").contains("使用 /opt/py/bin/python3;"));
+ }
+
#[test]
fn the_error_count_reads_in_each_language() {
assert_eq!((EN.errors)(1), "1 error");
diff --git a/docs/assets/settings-previews/build-tools-zh-Hans-dark.png b/docs/assets/settings-previews/build-tools-zh-Hans-dark.png
index 90ddd10..cd84b2b 100644
Binary files a/docs/assets/settings-previews/build-tools-zh-Hans-dark.png and b/docs/assets/settings-previews/build-tools-zh-Hans-dark.png differ
diff --git a/docs/assets/settings-previews/language-en-draft-light.png b/docs/assets/settings-previews/language-en-draft-light.png
index f9c71dd..7a97759 100644
Binary files a/docs/assets/settings-previews/language-en-draft-light.png and b/docs/assets/settings-previews/language-en-draft-light.png differ
diff --git a/docs/assets/settings-previews/language-zh-Hans-dark.png b/docs/assets/settings-previews/language-zh-Hans-dark.png
index cc7450a..30249e7 100644
Binary files a/docs/assets/settings-previews/language-zh-Hans-dark.png and b/docs/assets/settings-previews/language-zh-Hans-dark.png differ
diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md
index 69be3b6..07e9c60 100644
--- a/docs/feature-matrix.md
+++ b/docs/feature-matrix.md
@@ -12,14 +12,15 @@
| 能力域 | 功能项 | `darwin-arm64` | `darwin-x64` | `windows-x64` / `windows-arm64` | `linux-x64` / `linux-arm64` | 最近实机验证 | 实现与测试证据路径(本仓库) |
| --- | --- | --- | --- | --- | --- | --- | --- |
-| Python 设置效果预览 (`settingRegions`) | 「语言与框架 → Python」顶部显示当前解释器(工具行,点击到「工具链」页),下面四张卡片画出类型检查模式(含隐藏类型错误)、诊断范围、自动导入补全和补全函数括号的效果,随设置草稿更新。「构建工具 → Python」画出解释器的三步查找顺序和用途。预览使用固定示例,保存仍由宿主表单处理。 | ✅ 包内后端与无头设置窗口通过 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | `2026-11-23`(`darwin-arm64`,固定宿主 `60885168`,中文深色与英文浅色、草稿、窗口变宽) | `backend/src/view/`
`scripts/test.mjs`
`e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go` |
+| Python 设置效果预览 (`settingRegions`) | 「语言与框架 → Python」顶部显示当前解释器(工具行,点击到「工具链」页),设置了覆盖路径时下面多一行说明;四张卡片画出类型检查模式(按「显示类型错误」的四档画实际效果)、诊断范围、自动导入补全和补全函数括号的效果,随设置草稿更新。「构建工具 → Python」先画覆盖路径,再画解释器的三步查找顺序和用途。预览使用固定示例,保存仍由宿主表单处理。 | ✅ 包内后端与无头设置窗口通过 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | `2026-11-23`(`darwin-arm64`,固定宿主 `60885168`,中文深色与英文浅色、草稿、窗口变宽) | `backend/src/view/`
`scripts/test.mjs`
`e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go` |
+| Python 解释器覆盖设置 | 「设置 → 语言与框架 → Python」的 `pythonExecutable` 覆盖路径:构建任务、当前文件运行、手动运行和 pytest 用它,不按工具链查找;Pyrefly 和调试仍用工具链解析出的解释器。已保存的值继续读取。 | ✅ 已验证(macOS ARM64,当前文件运行端到端) | ⏳ 平台清单已验证 | ⏳ 平台清单已验证 | ⏳ 平台清单已验证 | `2026-11-23`(`darwin-arm64`,Lithe 0.8.9 与固定宿主 `60885168`) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/package/archives.test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` |
| 语言基础 (`languages`) | `.py` / `.pyi` / `.pyw` 识别、`#` 行注释、括号/引号配对、项目标记与 `.venv` / `venv` / `.conda` 依赖目录 | ✅ 已验证 | ⏳ pending(归档与清单已校验) | ⏳ pending(归档与 Windows 清单已校验) | ⏳ pending(归档与清单已校验) | `2026-11-20`(`darwin-arm64`,0.8.9 复验 `.py` 高亮) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` |
| 无后缀 Python 脚本 | 支持 TextMate 首行匹配的桌面按解释器路径或 `env` shebang 打开,提供 Python 高亮、注释与 Pyrefly 诊断 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | `2026-11-20`(`darwin-arm64`,桌面 `645a3aee8`) | `io.github.lithe-idea.python-support/grammars/python.first-line.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` |
| 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 包内 Rust SDK 后端协商 `litheLogging` 0 与 `litheFunctions` 0。解析 `pyrefly lsp` 启动,传入宿主提供的解释器,缺失时使用 Pyrefly 原生检测。 | ✅ 已验证(桌面主线) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `backend/src/pyrefly.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` |
| 工具链与环境自动发现 (`toolDefinitions`) | `python` 4 层解析:项目绑定 → `.venv` / `venv` / `.conda`(受工作区信任门控,保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` + `PATH` → 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。Homebrew 规则保留,但它的 `libexec/bin/python3` 链接到安装目录外,Core 目前以 `unsafePath` 跳过([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316))。 | ✅ 已验证 | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与环境变量发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
| 构建模型与运行 (`buildSystems: python` + `provider`) | `scripts/build_provider.py`(`python -I -B`,`lithe/build/model`)复用 `scripts/build_model.py` 纯 AST + `tomllib` / `vendor/tomli` 静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 7 类声明式 `run` 配置;支持损坏 `pyproject.toml` 降级与修复后恢复诊断,并在协商 `litheBuild` 1 时支持 `lithe/build/runEntrypoints` | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
-| 当前文件运行 (`buildProviders: 1`) | 工具栏支持带 `__main__` 入口的脚本或包内 `__main__.py`。使用工具链解析出的解释器,包括在「工具链」页为项目固定的解释器。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(macOS ARM64,Lithe 0.8.9 与固定宿主 `60885168` 工作台端到端,含固定解释器) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` |
-| 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用工具链为项目解析出的解释器。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(Lithe 0.8.9 与固定宿主 `60885168`,脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` |
+| 当前文件运行 (`buildProviders: 1`) | 工具栏支持带 `__main__` 入口的脚本或包内 `__main__.py`。使用工具链解析出的解释器(包括在「工具链」页为项目固定的解释器),设置了覆盖路径时用覆盖路径。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(macOS ARM64,Lithe 0.8.9 与固定宿主 `60885168` 工作台端到端,含固定解释器与覆盖路径) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` |
+| 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用工具链为项目解析出的解释器,设置了覆盖路径时用覆盖路径。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(Lithe 0.8.9 与固定宿主 `60885168`,脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` |
| 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时用 `python -I -B` 读取所选 Python 环境中已安装的包、版本和依赖关系,跳过用户级 site-packages 及其启动钩子,解析 PEP 508 条件和可选依赖。仅有 Conda 环境清单的项目也可加载。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` |
| 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(桌面主线) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
| 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
@@ -33,7 +34,7 @@
- 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1`、`buildProviders: 1`、`runConfigurationTypes: 0` 和 `languages: 0`。桌面 0.8.9 支持安装、当前文件运行和原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。
- `e2e/host/lithe-host.json` 固定桌面主线提交 `60885168`。
-- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮、当前文件运行(含为项目固定的解释器)、手动运行配置和依赖树,并在固定的桌面主线上运行完整宿主套件,额外覆盖设置预览、项目生成、解释器切换、pytest、debugpy 和无后缀脚本的编辑诊断。
+- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮、当前文件运行(含为项目固定的解释器和覆盖路径)、手动运行配置和依赖树,并在固定的桌面主线上运行完整宿主套件,额外覆盖设置预览、项目生成、解释器切换、pytest、debugpy 和无后缀脚本的编辑诊断。
- macOS ARM64 的工作台测试从 ZIP 安装插件,改变项目版本要求以切换外部解释器,检查全局候选和项目 `.venv` 信任,精确重跑一个参数化 pytest 用例并核对 JUnit。
- 无头工作台打开 `.py` 后,Pyrefly 返回所选环境独有模块的类型诊断。debugpy 使用同一环境执行当前文件,并将日志写入宿主分配目录。关闭后,已安装插件的文件清单和 SHA-256 与启动前一致。
- 宿主按 Core 的文件事实校验安装。程序链接到安装目录外的安装会以 `unsafePath` 被拒绝,包括在 macOS 和 Linux 上建在项目外的虚拟环境(venv、`uv venv`、virtualenv、Poetry、Pipenv)和 Homebrew 的 Python,固定、`VIRTUAL_ENV` 和发现规则都一样([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316))。项目内环境由宿主信任流程单独处理。所以固定解释器的端到端用例固定的是 `PYTEST_PYTHON` 指向的真实安装。
diff --git a/docs/releases/v1.1.0.md b/docs/releases/v1.1.0.md
index 53ebc77..6c7265e 100644
--- a/docs/releases/v1.1.0.md
+++ b/docs/releases/v1.1.0.md
@@ -1,51 +1,47 @@
## 中文
- 「设置 › 语言与框架 › Python」顶部显示当前使用的 Python 解释器,点击可打开「工具链」页更换。下面的预览卡片按尚未保存的设置画出类型检查模式、诊断范围、自动导入补全和补全函数括号的效果。
-- 「设置 › 构建、执行、部署 › 构建工具 › Python」显示 Lithe 查找解释器的顺序:项目固定的解释器和项目里的 `.venv`、`venv`、`.conda`,然后是全局设置,最后是自动发现。
-- Pyrefly 分析、运行、测试和调试都使用「工具链」页为项目解析出的同一个解释器。
-- 新增「隐藏类型错误」,替代原来的「显示类型错误」。开启后所有文件都不显示类型错误,包括有自己 Pyrefly 配置的项目;悬停、跳转和补全照常可用。
+- 「设置 › 构建、执行、部署 › 构建工具 › Python」显示 Lithe 查找解释器的顺序:项目固定的解释器和项目里的 `.venv`、`venv`、`.conda`,然后是全局设置,最后是自动发现;最前面标出「Python 解释器覆盖路径」是否设置,以及设置后哪些流程改用它。
+- 设置了「Python 解释器覆盖路径」时,语言页的解释器下面会说明:构建任务、运行和 pytest 用覆盖路径,Pyrefly 分析和调试仍用「工具链」页解析出的解释器。
+- 「显示类型错误」的四档现在都按标题生效。以前随包的 Pyrefly 1.4.1 只认“关闭”,其他两档和“始终开启”效果一样:
+ - 始终开启:所有文件都显示,没有 Pyrefly 配置的文件按类型检查模式检查;
+ - 仅已配置项目:只有 `pyrefly.toml` 或 `[tool.pyrefly]` 覆盖的文件显示;
+ - 仅报告缺失导入:Pyrefly 已经没有这个模式,没有 Pyrefly 配置的文件改按“基础”检查,报告无法解析的导入和少数 Pyrefly 确定的错误;
+ - 关闭:所有文件都不显示,包括有自己 Pyrefly 配置的项目。
+
+ 悬停、跳转和补全在各档都照常可用。
- 类型检查模式新增“宽松”预设。“自动”会沿用附近的 mypy 或 Pyright 配置,没有时按“基础”检查。
-- 类型检查模式和自动导入路径风格的说明写明了它们和其他设置的关系,例如开启「隐藏类型错误」后预设不再显示类型错误,关闭「自动导入补全」后只有代码操作会用到路径风格。
+- 类型检查模式和自动导入路径风格的说明写明了它们和其他设置的关系,例如「显示类型错误」不是“始终开启”时预设怎样生效,关闭「自动导入补全」后只有代码操作会用到路径风格。
### 升级与兼容性
-Python Support v1.1.0 要求 Lithe 0.8.9 或更新版本。从 0.8.10 开始,Lithe 还能按 shebang 自动识别无后缀脚本。
+Python Support v1.1.0 要求 Lithe 0.8.9 或更新版本。从 0.8.10 开始,Lithe 还能按 shebang 自动识别无后缀脚本。已经保存的设置都继续生效。
-v1.1.0 删除了「Python 解释器覆盖路径」设置。升级后,已经保存的路径不再生效,请在「设置 › 构建、执行、部署 › 工具链」为项目固定解释器。
+调试需要 Python 3.10 或更新版本。内置的 debugpy 1.8.22 不支持 Python 3.9,以前在 3.9 上启动调试会直接退出、没有任何提示;现在 Lithe 会在启动调试前检查解释器版本。运行、测试和依赖树仍支持 Python 3.9。macOS 自带的 `/usr/bin/python3` 是 3.9,调试请在「工具链」页改用 uv、pyenv 或 python.org 安装的 Python 3.10 以上版本,或项目里用它们建的 `.venv`。
-调试需要 Python 3.10 或更新版本。内置的 debugpy 1.8.22 不支持 Python 3.9,以前在 3.9 上启动调试会直接退出、没有任何提示;现在 Lithe 会在启动调试前检查解释器版本。运行、测试和依赖树仍支持 Python 3.9。
-
-原来的「显示类型错误」选择不会迁移到新设置:
-
-- 选过“关闭”的,请开启「隐藏类型错误」。
-- 选过“仅已配置项目”的,请把类型检查模式设为“关闭”。有自己 Pyrefly 配置的项目仍按项目配置检查。
-- “仅报告缺失导入”不再提供。
-
-已知限制:在 macOS 和 Linux 上,建在项目外的虚拟环境(`python -m venv`、`uv venv`、virtualenv,以及 Poetry、Pipenv 默认建的环境)和 Homebrew 安装的 Python 暂时不能选作解释器([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316))。在此之前,可以把环境建在项目里的 `.venv`(Poetry 用 `poetry config virtualenvs.in-project true`,Pipenv 设 `PIPENV_VENV_IN_PROJECT=1`),或者固定 uv、pyenv、python.org 安装的解释器。
+已知限制:在 macOS 和 Linux 上,建在项目外的虚拟环境(`python -m venv`、`uv venv`、virtualenv,以及 Poetry、Pipenv 默认建的环境)和 Homebrew 安装的 Python 暂时不能在「工具链」页选作解释器([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316))。在此之前,可以把环境建在项目里的 `.venv`(Poetry 用 `poetry config virtualenvs.in-project true`,Pipenv 设 `PIPENV_VENV_IN_PROJECT=1`),或者固定 uv、pyenv、python.org 安装的解释器;只需要运行和 pytest 时,也可以把环境里的 `python` 填进「Python 解释器覆盖路径」。
---
## English
- **Settings › Languages & Frameworks › Python** now shows the Python interpreter in use at the top. Click it to change it on the Toolchains page. The preview cards below draw the effect of the type checking mode, diagnostic scope, auto-import completions and function parentheses, following settings you have not saved yet.
-- **Settings › Build, Execution, Deployment › Build Tools › Python** shows the order in which Lithe looks for an interpreter: the project's pinned interpreter and its `.venv`, `venv` or `.conda`, then the global setting, then automatic discovery.
-- Pyrefly analysis, runs, tests and debugging all use the one interpreter the Toolchains page resolves for the project.
-- **Hide type errors** replaces **Display type errors**. When it is on, no file shows type errors, including projects with their own Pyrefly config. Hover, go to definition and completion keep working.
+- **Settings › Build, Execution, Deployment › Build Tools › Python** shows the order in which Lithe looks for an interpreter: the project's pinned interpreter and its `.venv`, `venv` or `.conda`, then the global setting, then automatic discovery. It first shows whether **Python executable override** is set, and which work uses it when it is.
+- When **Python executable override** is set, the language page says so under the interpreter: build tasks, runs and pytest use the override, while Pyrefly analysis and debugging still use the interpreter the Toolchains page resolves.
+- All four **Display type errors** choices now do what their titles say. The bundled Pyrefly 1.4.1 used to honor only **Off**, and the other two choices behaved like **Always on**:
+ - **Always on**: every file shows type errors, and files without a Pyrefly config are checked by the type checking mode.
+ - **Configured projects only**: only files a `pyrefly.toml` or `[tool.pyrefly]` covers show them.
+ - **Missing imports only**: Pyrefly no longer has this mode, so files without a Pyrefly config are checked as **Basic**, which reports unresolved imports and a few other errors Pyrefly is sure of.
+ - **Off**: no file shows them, including projects with their own Pyrefly config.
+
+ Hover, go to definition and completion keep working with every choice.
- The type checking mode has a new **Legacy** preset. **Automatic** follows a nearby mypy or Pyright config, and checks as **Basic** when there is none.
-- The descriptions of the type checking mode and the auto-import module path style now explain how they depend on other settings. For example, no preset shows type errors while **Hide type errors** is on, and with **Auto-import completions** off only code actions use the path style.
+- The descriptions of the type checking mode and the auto-import module path style now explain how they depend on other settings. For example, they say how the preset applies when **Display type errors** is not **Always on**, and that with **Auto-import completions** off only code actions use the path style.
### Upgrade and compatibility
-Python Support v1.1.0 requires Lithe 0.8.9 or later. Starting with 0.8.10, Lithe can also recognize extensionless scripts by their shebang.
-
-v1.1.0 removes the **Python executable override** setting. After you upgrade, a saved path no longer applies. Pin the interpreter for the project in **Settings › Build, Execution, Deployment › Toolchains** instead.
-
-Debugging requires Python 3.10 or later. The bundled debugpy 1.8.22 does not support Python 3.9, and starting a debug session on 3.9 used to exit without any message. Lithe now checks the interpreter version before it starts debugging. Runs, tests and the dependency tree still support Python 3.9.
-
-Your **Display type errors** choice does not carry over to the new setting:
+Python Support v1.1.0 requires Lithe 0.8.9 or later. Starting with 0.8.10, Lithe can also recognize extensionless scripts by their shebang. Settings you have saved keep working.
-- If you chose **Off**, turn on **Hide type errors**.
-- If you chose **Configured projects only**, set the type checking mode to **Off**. Projects with their own Pyrefly config are still checked by that config.
-- **Missing imports only** is no longer available.
+Debugging requires Python 3.10 or later. The bundled debugpy 1.8.22 does not support Python 3.9, and starting a debug session on 3.9 used to exit without any message. Lithe now checks the interpreter version before it starts debugging. Runs, tests and the dependency tree still support Python 3.9. The `/usr/bin/python3` that comes with macOS is 3.9, so to debug, choose Python 3.10 or later installed by uv, pyenv or python.org on the Toolchains page, or a `.venv` in the project made from one.
-Known limitation: on macOS and Linux, virtual environments outside the project (made by `python -m venv`, `uv venv` or virtualenv, and the environments Poetry and Pipenv create by default) and Homebrew Python cannot be chosen as the interpreter yet ([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316)). Until then, create the environment in the project as `.venv` (for Poetry, `poetry config virtualenvs.in-project true`; for Pipenv, set `PIPENV_VENV_IN_PROJECT=1`), or pin an interpreter installed by uv, pyenv or python.org.
+Known limitation: on macOS and Linux, virtual environments outside the project (made by `python -m venv`, `uv venv` or virtualenv, and the environments Poetry and Pipenv create by default) and Homebrew Python cannot be chosen on the Toolchains page yet ([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316)). Until then, create the environment in the project as `.venv` (for Poetry, `poetry config virtualenvs.in-project true`; for Pipenv, set `PIPENV_VENV_IN_PROJECT=1`), or pin an interpreter installed by uv, pyenv or python.org. If you only need runs and pytest, you can also enter the environment's `python` in **Python executable override**.
diff --git a/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go b/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go
index 766fe5f..b2cd035 100644
--- a/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go
+++ b/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go
@@ -3,6 +3,7 @@ package workbench
import (
"cmp"
"context"
+ "encoding/json"
"os"
"os/exec"
"path/filepath"
@@ -17,18 +18,39 @@ import (
"github.com/1lck/Lithe-IDEA/desktop/internal/toolchain"
)
+// pythonRunInterpreter is where a current-file run test expects the
+// interpreter to come from.
+type pythonRunInterpreter int
+
+const (
+ // The project's own .venv, found by the lookup.
+ projectEnvironment pythonRunInterpreter = iota
+ // An installation pinned for the project, as the Toolchains page does.
+ pinnedInstallation
+ // The Python executable override setting, which build, run and pytest
+ // use before the lookup.
+ executableOverride
+)
+
func TestPythonSupportPluginRunCurrentFile(t *testing.T) {
- checkPythonCurrentFileRun(t, false)
+ checkPythonCurrentFileRun(t, projectEnvironment)
}
// TestPythonSupportPluginRunCurrentFilePinnedInterpreter pins another
// interpreter for the project, as the Toolchains page does, and expects the
// run to use it over the project's .venv.
func TestPythonSupportPluginRunCurrentFilePinnedInterpreter(t *testing.T) {
- checkPythonCurrentFileRun(t, true)
+ checkPythonCurrentFileRun(t, pinnedInstallation)
}
-func checkPythonCurrentFileRun(t *testing.T, pinned bool) {
+// TestPythonSupportPluginRunCurrentFileInterpreterOverride sets the Python
+// executable override to an environment outside the project and expects the
+// run to use it over the project's .venv.
+func TestPythonSupportPluginRunCurrentFileInterpreterOverride(t *testing.T) {
+ checkPythonCurrentFileRun(t, executableOverride)
+}
+
+func checkPythonCurrentFileRun(t *testing.T, interpreter pythonRunInterpreter) {
t.Helper()
archive := pythonArchiveForE2E(t)
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
@@ -68,14 +90,37 @@ func checkPythonCurrentFileRun(t *testing.T, pinned bool) {
if _, err := trust.Save(ctx, kernel, true, false); err != nil {
t.Fatal(err)
}
+ wantPrefix := venv
+ if interpreter == executableOverride {
+ overrideDir, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantPrefix = filepath.Join(overrideDir, "configured interpreter")
+ if output, err := exec.CommandContext(ctx, python, "-m", "venv", "--without-pip", wantPrefix).CombinedOutput(); err != nil {
+ t.Fatalf("create configured environment: %v\n%s", err, output)
+ }
+ configured := filepath.Join(wantPrefix, "bin", "python")
+ if runtime.GOOS == "windows" {
+ configured = filepath.Join(wantPrefix, "Scripts", "python.exe")
+ }
+ settings, err := json.Marshal(map[string]map[string]string{
+ pythonSupportPluginID: {"pythonExecutable": configured},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(preferences.Dir(), "plugin-settings.json"), settings, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
h := newHarnessWithOptions(t, Options{
Kernel: kernel, PluginKernel: kernel, PluginRoot: t.TempDir(), Store: preferences,
Languages: []string{"en"},
})
installPythonArchive(t, ctx, h.app.plugins, archive)
h.app.reloadPluginLanguages()
- wantPrefix := venv
- if pinned {
+ if interpreter == pinnedInstallation {
home, version := pythonInstallationForE2E(t, ctx, cmp.Or(os.Getenv("PYTEST_PYTHON"), python))
wantPrefix = home
addPythonInstallationForE2E(t, ctx, h, home)
diff --git a/io.github.lithe-idea.python-support/l10n/zh-Hans.json b/io.github.lithe-idea.python-support/l10n/zh-Hans.json
index 097580c..0703b34 100644
--- a/io.github.lithe-idea.python-support/l10n/zh-Hans.json
+++ b/io.github.lithe-idea.python-support/l10n/zh-Hans.json
@@ -27,9 +27,13 @@
}
},
"settings": {
+ "pythonExecutable": {
+ "title": "Python 解释器覆盖路径",
+ "description": "构建、运行和 pytest 命令使用的 Python 解释器路径。留空时使用「工具链」页为项目解析出的解释器(.venv、venv、.conda、VIRTUAL_ENV、PATH,或发现的 conda、uv、pyenv 安装)。Pyrefly 分析和调试始终使用「工具链」页的解释器。"
+ },
"typeCheckingMode": {
"title": "类型检查模式",
- "description": "Pyrefly 对没有 pyrefly.toml 或 [tool.pyrefly] 的文件使用的预设;项目自己的 Pyrefly 配置优先。“自动”沿用附近的 mypy 或 Pyright 配置,没有时按“基础”检查。开启“隐藏类型错误”后,选哪个预设都不显示类型错误。",
+ "description": "Pyrefly 对没有 pyrefly.toml 或 [tool.pyrefly] 的文件使用的预设;项目自己的 Pyrefly 配置优先。“自动”沿用附近的 mypy 或 Pyright 配置,没有时按“基础”检查。「显示类型错误」决定预设是否生效:选“仅已配置项目”时,没有 Pyrefly 配置的文件不显示类型错误;选“仅报告缺失导入”时,这些文件改按“基础”检查;选“关闭”时,所有文件都不显示。",
"options": {
"default": "默认",
"auto": "自动",
@@ -40,9 +44,15 @@
"all": "全部"
}
},
- "disableTypeErrors": {
- "title": "隐藏类型错误",
- "description": "开启后所有文件都不显示类型错误,包括有自己 Pyrefly 配置的项目;悬停、跳转和补全照常可用。"
+ "displayTypeErrors": {
+ "title": "显示类型错误",
+ "description": "Pyrefly 在哪些文件里显示类型错误:所有文件、只在 pyrefly.toml 或 [tool.pyrefly] 覆盖的文件里,或所有文件都不显示。Pyrefly 已经没有“只报告缺失导入”的模式,所以选“仅报告缺失导入”时,没有 Pyrefly 配置的文件按“基础”检查:报告无法解析的导入,以及少量 Pyrefly 确信的其他错误。选哪一项,悬停、跳转和补全都照常可用。",
+ "options": {
+ "force-on": "始终开启",
+ "default": "仅已配置项目",
+ "error-missing-imports": "仅报告缺失导入",
+ "force-off": "关闭"
+ }
},
"diagnosticMode": {
"title": "诊断范围",
@@ -78,6 +88,7 @@
}
},
"sections": {
+ "Python Interpreter": "Python 解释器",
"Pyrefly": "Pyrefly",
"Completions": "代码补全"
}
diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json
index 72e5358..4314669 100644
--- a/io.github.lithe-idea.python-support/plugin.json
+++ b/io.github.lithe-idea.python-support/plugin.json
@@ -95,11 +95,21 @@
}
],
"settings": [
+ {
+ "id": "pythonExecutable",
+ "type": "file",
+ "title": "Python executable override",
+ "description": "Explicit path to the Python interpreter for build, run, and pytest commands. Leave empty to use the interpreter the Toolchains page resolves for the project (.venv, venv, .conda, VIRTUAL_ENV, PATH, or discovered conda / uv / pyenv installations). Pyrefly analysis and debugging always use the Toolchains interpreter.",
+ "default": "",
+ "effect": "reload",
+ "page": { "languageID": "python" },
+ "section": "Python Interpreter"
+ },
{
"id": "typeCheckingMode",
"type": "enum",
"title": "Type checking mode",
- "description": "Pyrefly's preset for files no pyrefly.toml or [tool.pyrefly] covers; a project's own Pyrefly config wins. Automatic follows a nearby mypy or Pyright config, else checks as Basic. While Hide type errors is on, no preset shows type errors.",
+ "description": "Pyrefly's preset for files no pyrefly.toml or [tool.pyrefly] covers; a project's own Pyrefly config wins. Automatic follows a nearby mypy or Pyright config, else checks as Basic. Display type errors decides whether the preset applies: Configured projects only shows no type errors in files without a Pyrefly config, Missing imports only checks them as Basic instead, and Off shows none in any file.",
"default": "default",
"options": [
{ "value": "default", "title": "Default" },
@@ -115,11 +125,17 @@
"section": "Pyrefly"
},
{
- "id": "disableTypeErrors",
- "type": "boolean",
- "title": "Hide type errors",
- "description": "Hide type errors in every file, including projects with their own Pyrefly config. Hover, go to definition and completion keep working.",
- "default": false,
+ "id": "displayTypeErrors",
+ "type": "enum",
+ "title": "Display type errors",
+ "description": "Where Pyrefly shows type errors: in every file, only in files a pyrefly.toml or [tool.pyrefly] covers, or in no file. Pyrefly no longer has a missing-imports-only mode, so Missing imports only checks files without a Pyrefly config as Basic, which reports unresolved imports and a few other errors Pyrefly is sure of. Hover, go to definition and completion keep working in every mode.",
+ "default": "force-on",
+ "options": [
+ { "value": "force-on", "title": "Always on" },
+ { "value": "default", "title": "Configured projects only" },
+ { "value": "error-missing-imports", "title": "Missing imports only" },
+ { "value": "force-off", "title": "Off" }
+ ],
"effect": "immediate",
"page": { "languageID": "python" },
"section": "Pyrefly"
@@ -206,7 +222,7 @@
"python": {
"pyrefly": {
"typeCheckingMode": "${setting:typeCheckingMode}",
- "disableTypeErrors": "${setting:disableTypeErrors}",
+ "displayTypeErrors": "${setting:displayTypeErrors}",
"diagnosticMode": "${setting:diagnosticMode}"
},
"analysis": {
@@ -496,6 +512,7 @@
},
"invocation": {
"executables": [
+ { "kind": "setting", "settingID": "pythonExecutable" },
{ "kind": "toolchain", "toolchainID": "python" }
],
"version": {
@@ -512,6 +529,7 @@
"runtimeArguments": ["-I", "-B"],
"entry": "scripts/build_provider.py"
},
+ "initializationOptions": { "pythonExecutable": "${setting:pythonExecutable}" },
"executesProjectCode": true,
"mayUseNetwork": false
},
diff --git a/io.github.lithe-idea.python-support/scripts/build_provider.py b/io.github.lithe-idea.python-support/scripts/build_provider.py
index f52cd0f..f050271 100644
--- a/io.github.lithe-idea.python-support/scripts/build_provider.py
+++ b/io.github.lithe-idea.python-support/scripts/build_provider.py
@@ -184,10 +184,14 @@ def create_build_provider_server() -> JsonRpcServer:
workspace_root_holder: dict[str, Path] = {"root": Path.cwd().resolve()}
degraded_model_roots: set[str] = set()
state_lock = threading.Lock()
+ configured_interpreter = False
locale = ""
def _on_init(params: dict[str, Any]) -> None:
- nonlocal locale
+ nonlocal configured_interpreter, locale
+ initialization = params.get("initializationOptions")
+ if isinstance(initialization, dict):
+ configured_interpreter = bool(initialization.get("pythonExecutable"))
if isinstance(params.get("locale"), str):
locale = params["locale"]
folders = params.get("workspaceFolders")
@@ -225,6 +229,11 @@ def _resolve_runtime_and_env(params: dict[str, Any]) -> tuple[str, dict[str, str
raw_exec = tool.get("executable")
if isinstance(raw_exec, str) and raw_exec.strip():
python_exec = raw_exec.strip()
+ options = params.get("options")
+ if isinstance(options, dict):
+ opt_exec = options.get("pythonExecutable")
+ if isinstance(opt_exec, str) and opt_exec.strip():
+ python_exec = opt_exec.strip()
env = dict(os.environ)
raw_env = params.get("environment")
@@ -412,6 +421,13 @@ def handle_prepare_run(params: dict[str, Any], ctx: CallContext) -> dict[str, An
*_string_args(params.get("optionArguments")),
*_string_args(launch.get("arguments", params.get("userArguments"))),
]
+ if configured_interpreter:
+ tool = params.get("tool")
+ executable = tool.get("executable") if isinstance(tool, dict) else None
+ if not isinstance(executable, str) or not Path(executable).is_absolute():
+ raise PluginError("python.interpreterUnavailable", run_message("interpreter", locale))
+ environment.setdefault("PYTHON_EXECUTABLE", executable)
+ arguments = ["-I", "-B", _ENTRYPOINT_LAUNCHER, "interpreter", executable, *arguments]
return {
"executable": {"kind": "toolchain", "value": "python"},
"arguments": arguments,
diff --git a/io.github.lithe-idea.python-support/scripts/run_entrypoint.py b/io.github.lithe-idea.python-support/scripts/run_entrypoint.py
index f7ff4cb..1aca606 100644
--- a/io.github.lithe-idea.python-support/scripts/run_entrypoint.py
+++ b/io.github.lithe-idea.python-support/scripts/run_entrypoint.py
@@ -1,5 +1,6 @@
"""Launch Python entrypoints within the process tree owned by the host."""
+import os
import sys
from importlib import import_module
from importlib.util import find_spec, module_from_spec
@@ -15,6 +16,10 @@
"The saved Python entrypoint is no longer available. Open the file and run it again.",
"保存的 Python 入口已失效。请打开文件并重新运行。",
),
+ "interpreter": (
+ "Lithe could not resolve the configured Python interpreter. Check the Python executable override.",
+ "Lithe 无法解析配置的 Python 解释器。请检查 Python 解释器覆盖设置。",
+ ),
"shadowed": (
"A module or package with the same name shadows the selected Python entrypoint.",
"当前包入口被同名模块或包遮蔽。",
@@ -30,6 +35,18 @@ def run_message(key: str, locale: str) -> str:
return chinese if locale.replace("_", "-").split("-", 1)[0].lower() == "zh" else english
+def _run_with_interpreter(executable: str, args: list[str]) -> int:
+ # Match the build invocation's executable-directory PATH precedence.
+ os.environ["PATH"] = os.pathsep.join(filter(None, (str(Path(executable).parent), os.environ.get("PATH"))))
+ argv = [executable, *args]
+ if os.name == "nt":
+ import subprocess
+
+ # The host's Job Object owns this child. Keep the parent alive to report its exit code.
+ return subprocess.call(argv, executable=executable)
+ os.execv(executable, argv)
+
+
def _run_package(import_root: str, package: str, selected_file: str, locale: str, args: list[str]) -> int:
source = Path(selected_file).resolve()
if sys.path and sys.path[0] == str(Path(__file__).parent):
@@ -64,5 +81,8 @@ def _run_package(import_root: str, package: str, selected_file: str, locale: str
if __name__ == "__main__":
- _package_action, import_root, package, selected_file, locale, *program_args = sys.argv[1:]
+ action, *args = sys.argv[1:]
+ if action == "interpreter":
+ raise SystemExit(_run_with_interpreter(args[0], args[1:]))
+ import_root, package, selected_file, locale, *program_args = args
raise SystemExit(_run_package(import_root, package, selected_file, locale, program_args))
diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs
index a12ad76..ca81780 100644
--- a/scripts/package/archives.test.mjs
+++ b/scripts/package/archives.test.mjs
@@ -11,7 +11,7 @@ const baseManifest = JSON.parse(readFileSync(`${PACKAGE_ID}/plugin.json`, "utf8"
const lock = JSON.parse(readFileSync("vendor-lock.json", "utf8"));
const version = baseManifest.version;
-test("every platform shows the settings views on the Python language and build pages, with no interpreter override", () => {
+test("every platform shows the settings views and the interpreter override on the Python pages", () => {
for (const platform of Object.keys(lock.pyrefly.platforms)) {
const manifest = manifestForPlatform(baseManifest, platform, lock);
assert.deepEqual(
@@ -22,8 +22,8 @@ test("every platform shows the settings views on the Python language and build p
],
platform,
);
- // The interpreter is the python tool's pin on the Toolchains page.
- assert.equal(manifest.settings.find(({ id }) => id === "pythonExecutable"), undefined, platform);
+ const interpreter = manifest.settings.find(({ id }) => id === "pythonExecutable");
+ assert.deepEqual(interpreter?.page, { languageID: "python" }, platform);
}
});
diff --git a/scripts/test.mjs b/scripts/test.mjs
index 96f9026..773847c 100644
--- a/scripts/test.mjs
+++ b/scripts/test.mjs
@@ -744,16 +744,19 @@ try {
params: { operationID: "op-preview-draft", functionID: region.view.function,
params: { ...previewEvent, event: "settings", language: "zh-Hans", width: 360,
settings: { ...previewEvent.settings, draft: {
- disableTypeErrors: true, completeFunctionParens: true, importFormat: "relative",
+ displayTypeErrors: "force-off", completeFunctionParens: true, importFormat: "relative",
+ pythonExecutable: "/opt/python/bin/python3",
} } } },
});
const drafted = await peer.waitFor((m) => m.id === 22, "Python preview draft");
- const [, narrow] = drafted.result.view;
+ const [draftSection, narrow] = drafted.result.view;
+ assert.equal(draftSection.children[1].type, "banner");
+ assert.match(draftSection.children[1].text, /\/opt\/python\/bin\/python3/);
assert.equal(narrow.viewBox[2], 360);
assert.ok(narrow.height > wide.height);
const drawn = JSON.stringify(narrow);
assert.match(drawn, /含未应用的修改/);
- assert.match(drawn, /"text":"已隐藏"/);
+ assert.match(drawn, /「显示类型错误」已关闭/);
assert.doesNotMatch(drawn, /bad-argument-type/);
assert.match(drawn, /"text":"相对导入"/);
assert.match(drawn, /补全函数时加上括号/);
@@ -771,7 +774,7 @@ try {
assert.deepEqual(toolRow, { type: "tool", tool: "python" });
assert.equal(order.id, "python-resolution");
assert.equal(order.on, undefined);
- assert.match(JSON.stringify(order), /Tried first[\s\S]*Global default[\s\S]*Tried last[\s\S]*Pyrefly uses the same interpreter/);
+ assert.match(JSON.stringify(order), /Python executable override[\s\S]*Not set[\s\S]*Tried first[\s\S]*Global default[\s\S]*Tried last[\s\S]*Pyrefly uses the interpreter found/);
assert.ok(!peer.allReceived.some((m) =>
m.method === "lithe/log" && ["op-preview-open", "op-preview-draft", "op-preview-lookup"].includes(m.params?.operationId),
), "Successful preview events should not produce logs");
@@ -794,7 +797,7 @@ try {
temporaryDirectory: tempDir,
settings: {
typeCheckingMode: "strict",
- disableTypeErrors: false,
+ displayTypeErrors: "force-on",
diagnosticMode: "openFilesOnly",
autoImportCompletions: true,
completeFunctionParens: true,
@@ -818,6 +821,8 @@ try {
});
assert.deepEqual(resolvedUnixAnswer.arguments, ["lsp"]);
assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pythonPath, extPython);
+ // Pyrefly 1.4.1 lets typeCheckingMode and disableTypeErrors win over the
+ // deprecated displayTypeErrors, so the answer sends only the new pair.
assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pyrefly.typeCheckingMode, "strict");
assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pyrefly.disableTypeErrors, false);
assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pyrefly.displayTypeErrors, undefined);
@@ -1773,6 +1778,16 @@ try {
assert.equal(collision.status, 1);
assert.match(collision.stderr, /当前包入口被同名模块或包遮蔽/);
+ const launcher = join(unpackedPluginDir, "scripts", "run_entrypoint.py");
+ const interpreter = run(pythonCmd, ["-c", "import sys; print(sys.executable)"]).trim();
+ const forwarded = spawnSync(pythonCmd, ["-I", "-B", launcher, "interpreter", interpreter,
+ "-c", "import sys; print(sys.argv[1]); sys.exit(17)", "argument with spaces"], {
+ cwd: wsDir, encoding: "utf8", timeout: 5000, windowsHide: true,
+ });
+ assert.ifError(forwarded.error);
+ assert.equal(forwarded.status, 17, forwarded.stderr);
+ assert.equal(forwarded.stdout.trim(), "argument with spaces");
+
for (const [id, entrypoint] of [[73, "script:../worker.py"], [74, "script:missing.py"]]) {
const response = await prepareRun(id, { entrypoint });
assert.equal(response.error?.code, -32000);