1use anyhow::{Context as _, ensure};
2use anyhow::{Result, anyhow};
3use async_trait::async_trait;
4use collections::HashMap;
5use gpui::{App, Task};
6use gpui::{AsyncApp, SharedString};
7use language::ToolchainList;
8use language::ToolchainLister;
9use language::language_settings::language_settings;
10use language::{ContextLocation, LanguageToolchainStore};
11use language::{ContextProvider, LspAdapter, LspAdapterDelegate};
12use language::{LanguageName, ManifestName, ManifestProvider, ManifestQuery};
13use language::{Toolchain, WorkspaceFoldersContent};
14use lsp::LanguageServerBinary;
15use lsp::LanguageServerName;
16use node_runtime::{NodeRuntime, VersionStrategy};
17use pet_core::Configuration;
18use pet_core::os_environment::Environment;
19use pet_core::python_environment::PythonEnvironmentKind;
20use project::Fs;
21use project::lsp_store::language_server_settings;
22use serde_json::{Value, json};
23use smol::lock::OnceCell;
24use std::cmp::Ordering;
25
26use parking_lot::Mutex;
27use std::str::FromStr;
28use std::{
29 any::Any,
30 borrow::Cow,
31 ffi::OsString,
32 fmt::Write,
33 fs,
34 io::{self, BufRead},
35 path::{Path, PathBuf},
36 sync::Arc,
37};
38use task::{TaskTemplate, TaskTemplates, VariableName};
39use util::ResultExt;
40
41pub(crate) struct PyprojectTomlManifestProvider;
42
43impl ManifestProvider for PyprojectTomlManifestProvider {
44 fn name(&self) -> ManifestName {
45 SharedString::new_static("pyproject.toml").into()
46 }
47
48 fn search(
49 &self,
50 ManifestQuery {
51 path,
52 depth,
53 delegate,
54 }: ManifestQuery,
55 ) -> Option<Arc<Path>> {
56 for path in path.ancestors().take(depth) {
57 let p = path.join("pyproject.toml");
58 if delegate.exists(&p, Some(false)) {
59 return Some(path.into());
60 }
61 }
62
63 None
64 }
65}
66
67const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
68const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
69
70enum TestRunner {
71 UNITTEST,
72 PYTEST,
73}
74
75impl FromStr for TestRunner {
76 type Err = ();
77
78 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
79 match s {
80 "unittest" => Ok(Self::UNITTEST),
81 "pytest" => Ok(Self::PYTEST),
82 _ => Err(()),
83 }
84 }
85}
86
87fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
88 vec![server_path.into(), "--stdio".into()]
89}
90
91pub struct PythonLspAdapter {
92 node: NodeRuntime,
93}
94
95impl PythonLspAdapter {
96 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
97
98 pub fn new(node: NodeRuntime) -> Self {
99 PythonLspAdapter { node }
100 }
101}
102
103#[async_trait(?Send)]
104impl LspAdapter for PythonLspAdapter {
105 fn name(&self) -> LanguageServerName {
106 Self::SERVER_NAME.clone()
107 }
108
109 async fn initialization_options(
110 self: Arc<Self>,
111 _: &dyn Fs,
112 _: &Arc<dyn LspAdapterDelegate>,
113 ) -> Result<Option<Value>> {
114 // Provide minimal initialization options
115 // Virtual environment configuration will be handled through workspace configuration
116 Ok(Some(json!({
117 "python": {
118 "analysis": {
119 "autoSearchPaths": true,
120 "useLibraryCodeForTypes": true,
121 "autoImportCompletions": true
122 }
123 }
124 })))
125 }
126
127 async fn check_if_user_installed(
128 &self,
129 delegate: &dyn LspAdapterDelegate,
130 _: Option<Toolchain>,
131 _: &AsyncApp,
132 ) -> Option<LanguageServerBinary> {
133 if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
134 let env = delegate.shell_env().await;
135 Some(LanguageServerBinary {
136 path: pyright_bin,
137 env: Some(env),
138 arguments: vec!["--stdio".into()],
139 })
140 } else {
141 let node = delegate.which("node".as_ref()).await?;
142 let (node_modules_path, _) = delegate
143 .npm_package_installed_version(Self::SERVER_NAME.as_ref())
144 .await
145 .log_err()??;
146
147 let path = node_modules_path.join(NODE_MODULE_RELATIVE_SERVER_PATH);
148
149 let env = delegate.shell_env().await;
150 Some(LanguageServerBinary {
151 path: node,
152 env: Some(env),
153 arguments: server_binary_arguments(&path),
154 })
155 }
156 }
157
158 async fn fetch_latest_server_version(
159 &self,
160 _: &dyn LspAdapterDelegate,
161 ) -> Result<Box<dyn 'static + Any + Send>> {
162 Ok(Box::new(
163 self.node
164 .npm_package_latest_version(Self::SERVER_NAME.as_ref())
165 .await?,
166 ) as Box<_>)
167 }
168
169 async fn fetch_server_binary(
170 &self,
171 latest_version: Box<dyn 'static + Send + Any>,
172 container_dir: PathBuf,
173 delegate: &dyn LspAdapterDelegate,
174 ) -> Result<LanguageServerBinary> {
175 let latest_version = latest_version.downcast::<String>().unwrap();
176 let server_path = container_dir.join(SERVER_PATH);
177
178 self.node
179 .npm_install_packages(
180 &container_dir,
181 &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
182 )
183 .await?;
184
185 let env = delegate.shell_env().await;
186 Ok(LanguageServerBinary {
187 path: self.node.binary_path().await?,
188 env: Some(env),
189 arguments: server_binary_arguments(&server_path),
190 })
191 }
192
193 async fn check_if_version_installed(
194 &self,
195 version: &(dyn 'static + Send + Any),
196 container_dir: &PathBuf,
197 delegate: &dyn LspAdapterDelegate,
198 ) -> Option<LanguageServerBinary> {
199 let version = version.downcast_ref::<String>().unwrap();
200 let server_path = container_dir.join(SERVER_PATH);
201
202 let should_install_language_server = self
203 .node
204 .should_install_npm_package(
205 Self::SERVER_NAME.as_ref(),
206 &server_path,
207 &container_dir,
208 VersionStrategy::Latest(version),
209 )
210 .await;
211
212 if should_install_language_server {
213 None
214 } else {
215 let env = delegate.shell_env().await;
216 Some(LanguageServerBinary {
217 path: self.node.binary_path().await.ok()?,
218 env: Some(env),
219 arguments: server_binary_arguments(&server_path),
220 })
221 }
222 }
223
224 async fn cached_server_binary(
225 &self,
226 container_dir: PathBuf,
227 delegate: &dyn LspAdapterDelegate,
228 ) -> Option<LanguageServerBinary> {
229 let mut binary = get_cached_server_binary(container_dir, &self.node).await?;
230 binary.env = Some(delegate.shell_env().await);
231 Some(binary)
232 }
233
234 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
235 // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
236 // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
237 // and `name` is the symbol name itself.
238 //
239 // Because the symbol name is included, there generally are not ties when
240 // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
241 // into account. Here, we remove the symbol name from the sortText in order
242 // to allow our own fuzzy score to be used to break ties.
243 //
244 // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
245 for item in items {
246 let Some(sort_text) = &mut item.sort_text else {
247 continue;
248 };
249 let mut parts = sort_text.split('.');
250 let Some(first) = parts.next() else { continue };
251 let Some(second) = parts.next() else { continue };
252 let Some(_) = parts.next() else { continue };
253 sort_text.replace_range(first.len() + second.len() + 1.., "");
254 }
255 }
256
257 async fn label_for_completion(
258 &self,
259 item: &lsp::CompletionItem,
260 language: &Arc<language::Language>,
261 ) -> Option<language::CodeLabel> {
262 let label = &item.label;
263 let grammar = language.grammar()?;
264 let highlight_id = match item.kind? {
265 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
266 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
267 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
268 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
269 _ => return None,
270 };
271 let filter_range = item
272 .filter_text
273 .as_deref()
274 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
275 .unwrap_or(0..label.len());
276 Some(language::CodeLabel {
277 text: label.clone(),
278 runs: vec![(0..label.len(), highlight_id)],
279 filter_range,
280 })
281 }
282
283 async fn label_for_symbol(
284 &self,
285 name: &str,
286 kind: lsp::SymbolKind,
287 language: &Arc<language::Language>,
288 ) -> Option<language::CodeLabel> {
289 let (text, filter_range, display_range) = match kind {
290 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
291 let text = format!("def {}():\n", name);
292 let filter_range = 4..4 + name.len();
293 let display_range = 0..filter_range.end;
294 (text, filter_range, display_range)
295 }
296 lsp::SymbolKind::CLASS => {
297 let text = format!("class {}:", name);
298 let filter_range = 6..6 + name.len();
299 let display_range = 0..filter_range.end;
300 (text, filter_range, display_range)
301 }
302 lsp::SymbolKind::CONSTANT => {
303 let text = format!("{} = 0", name);
304 let filter_range = 0..name.len();
305 let display_range = 0..filter_range.end;
306 (text, filter_range, display_range)
307 }
308 _ => return None,
309 };
310
311 Some(language::CodeLabel {
312 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
313 text: text[display_range].to_string(),
314 filter_range,
315 })
316 }
317
318 async fn workspace_configuration(
319 self: Arc<Self>,
320 _: &dyn Fs,
321 adapter: &Arc<dyn LspAdapterDelegate>,
322 toolchain: Option<Toolchain>,
323 cx: &mut AsyncApp,
324 ) -> Result<Value> {
325 cx.update(move |cx| {
326 let mut user_settings =
327 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
328 .and_then(|s| s.settings.clone())
329 .unwrap_or_default();
330
331 // If we have a detected toolchain, configure Pyright to use it
332 if let Some(toolchain) = toolchain {
333 if user_settings.is_null() {
334 user_settings = Value::Object(serde_json::Map::default());
335 }
336 let object = user_settings.as_object_mut().unwrap();
337
338 let interpreter_path = toolchain.path.to_string();
339
340 // Detect if this is a virtual environment
341 if let Some(interpreter_dir) = Path::new(&interpreter_path).parent() {
342 if let Some(venv_dir) = interpreter_dir.parent() {
343 // Check if this looks like a virtual environment
344 if venv_dir.join("pyvenv.cfg").exists()
345 || venv_dir.join("bin/activate").exists()
346 || venv_dir.join("Scripts/activate.bat").exists()
347 {
348 // Set venvPath and venv at the root level
349 // This matches the format of a pyrightconfig.json file
350 if let Some(parent) = venv_dir.parent() {
351 // Use relative path if the venv is inside the workspace
352 let venv_path = if parent == adapter.worktree_root_path() {
353 ".".to_string()
354 } else {
355 parent.to_string_lossy().into_owned()
356 };
357 object.insert("venvPath".to_string(), Value::String(venv_path));
358 }
359
360 if let Some(venv_name) = venv_dir.file_name() {
361 object.insert(
362 "venv".to_owned(),
363 Value::String(venv_name.to_string_lossy().into_owned()),
364 );
365 }
366 }
367 }
368 }
369
370 // Always set the python interpreter path
371 // Get or create the python section
372 let python = object
373 .entry("python")
374 .or_insert(Value::Object(serde_json::Map::default()))
375 .as_object_mut()
376 .unwrap();
377
378 // Set both pythonPath and defaultInterpreterPath for compatibility
379 python.insert(
380 "pythonPath".to_owned(),
381 Value::String(interpreter_path.clone()),
382 );
383 python.insert(
384 "defaultInterpreterPath".to_owned(),
385 Value::String(interpreter_path),
386 );
387 }
388
389 user_settings
390 })
391 }
392
393 fn workspace_folders_content(&self) -> WorkspaceFoldersContent {
394 WorkspaceFoldersContent::WorktreeRoot
395 }
396}
397
398async fn get_cached_server_binary(
399 container_dir: PathBuf,
400 node: &NodeRuntime,
401) -> Option<LanguageServerBinary> {
402 let server_path = container_dir.join(SERVER_PATH);
403 if server_path.exists() {
404 Some(LanguageServerBinary {
405 path: node.binary_path().await.log_err()?,
406 env: None,
407 arguments: server_binary_arguments(&server_path),
408 })
409 } else {
410 log::error!("missing executable in directory {:?}", server_path);
411 None
412 }
413}
414
415pub(crate) struct PythonContextProvider;
416
417const PYTHON_TEST_TARGET_TASK_VARIABLE: VariableName =
418 VariableName::Custom(Cow::Borrowed("PYTHON_TEST_TARGET"));
419
420const PYTHON_ACTIVE_TOOLCHAIN_PATH: VariableName =
421 VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN"));
422
423const PYTHON_ACTIVE_TOOLCHAIN_PATH_RAW: VariableName =
424 VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN_RAW"));
425
426const PYTHON_MODULE_NAME_TASK_VARIABLE: VariableName =
427 VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
428
429impl ContextProvider for PythonContextProvider {
430 fn build_context(
431 &self,
432 variables: &task::TaskVariables,
433 location: ContextLocation<'_>,
434 _: Option<HashMap<String, String>>,
435 toolchains: Arc<dyn LanguageToolchainStore>,
436 cx: &mut gpui::App,
437 ) -> Task<Result<task::TaskVariables>> {
438 let test_target =
439 match selected_test_runner(location.file_location.buffer.read(cx).file(), cx) {
440 TestRunner::UNITTEST => self.build_unittest_target(variables),
441 TestRunner::PYTEST => self.build_pytest_target(variables),
442 };
443
444 let module_target = self.build_module_target(variables);
445 let location_file = location.file_location.buffer.read(cx).file().cloned();
446 let worktree_id = location_file.as_ref().map(|f| f.worktree_id(cx));
447
448 cx.spawn(async move |cx| {
449 let raw_toolchain = if let Some(worktree_id) = worktree_id {
450 let file_path = location_file
451 .as_ref()
452 .and_then(|f| f.path().parent())
453 .map(Arc::from)
454 .unwrap_or_else(|| Arc::from("".as_ref()));
455
456 toolchains
457 .active_toolchain(worktree_id, file_path, "Python".into(), cx)
458 .await
459 .map_or_else(
460 || String::from("python3"),
461 |toolchain| toolchain.path.to_string(),
462 )
463 } else {
464 String::from("python3")
465 };
466
467 let active_toolchain = format!("\"{raw_toolchain}\"");
468 let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
469 let raw_toolchain_var = (PYTHON_ACTIVE_TOOLCHAIN_PATH_RAW, raw_toolchain);
470
471 Ok(task::TaskVariables::from_iter(
472 test_target
473 .into_iter()
474 .chain(module_target.into_iter())
475 .chain([toolchain, raw_toolchain_var]),
476 ))
477 })
478 }
479
480 fn associated_tasks(
481 &self,
482 _: Arc<dyn Fs>,
483 file: Option<Arc<dyn language::File>>,
484 cx: &App,
485 ) -> Task<Option<TaskTemplates>> {
486 let test_runner = selected_test_runner(file.as_ref(), cx);
487
488 let mut tasks = vec![
489 // Execute a selection
490 TaskTemplate {
491 label: "execute selection".to_owned(),
492 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
493 args: vec![
494 "-c".to_owned(),
495 VariableName::SelectedText.template_value_with_whitespace(),
496 ],
497 cwd: Some("$ZED_WORKTREE_ROOT".into()),
498 ..TaskTemplate::default()
499 },
500 // Execute an entire file
501 TaskTemplate {
502 label: format!("run '{}'", VariableName::File.template_value()),
503 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
504 args: vec![VariableName::File.template_value_with_whitespace()],
505 cwd: Some("$ZED_WORKTREE_ROOT".into()),
506 ..TaskTemplate::default()
507 },
508 // Execute a file as module
509 TaskTemplate {
510 label: format!("run module '{}'", VariableName::File.template_value()),
511 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
512 args: vec![
513 "-m".to_owned(),
514 PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
515 ],
516 cwd: Some("$ZED_WORKTREE_ROOT".into()),
517 tags: vec!["python-module-main-method".to_owned()],
518 ..TaskTemplate::default()
519 },
520 ];
521
522 tasks.extend(match test_runner {
523 TestRunner::UNITTEST => {
524 [
525 // Run tests for an entire file
526 TaskTemplate {
527 label: format!("unittest '{}'", VariableName::File.template_value()),
528 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
529 args: vec![
530 "-m".to_owned(),
531 "unittest".to_owned(),
532 VariableName::File.template_value_with_whitespace(),
533 ],
534 cwd: Some("$ZED_WORKTREE_ROOT".into()),
535 ..TaskTemplate::default()
536 },
537 // Run test(s) for a specific target within a file
538 TaskTemplate {
539 label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
540 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
541 args: vec![
542 "-m".to_owned(),
543 "unittest".to_owned(),
544 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
545 ],
546 tags: vec![
547 "python-unittest-class".to_owned(),
548 "python-unittest-method".to_owned(),
549 ],
550 cwd: Some("$ZED_WORKTREE_ROOT".into()),
551 ..TaskTemplate::default()
552 },
553 ]
554 }
555 TestRunner::PYTEST => {
556 [
557 // Run tests for an entire file
558 TaskTemplate {
559 label: format!("pytest '{}'", VariableName::File.template_value()),
560 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
561 args: vec![
562 "-m".to_owned(),
563 "pytest".to_owned(),
564 VariableName::File.template_value_with_whitespace(),
565 ],
566 cwd: Some("$ZED_WORKTREE_ROOT".into()),
567 ..TaskTemplate::default()
568 },
569 // Run test(s) for a specific target within a file
570 TaskTemplate {
571 label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
572 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
573 args: vec![
574 "-m".to_owned(),
575 "pytest".to_owned(),
576 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
577 ],
578 cwd: Some("$ZED_WORKTREE_ROOT".into()),
579 tags: vec![
580 "python-pytest-class".to_owned(),
581 "python-pytest-method".to_owned(),
582 ],
583 ..TaskTemplate::default()
584 },
585 ]
586 }
587 });
588
589 Task::ready(Some(TaskTemplates(tasks)))
590 }
591}
592
593fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
594 const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
595 language_settings(Some(LanguageName::new("Python")), location, cx)
596 .tasks
597 .variables
598 .get(TEST_RUNNER_VARIABLE)
599 .and_then(|val| TestRunner::from_str(val).ok())
600 .unwrap_or(TestRunner::PYTEST)
601}
602
603impl PythonContextProvider {
604 fn build_unittest_target(
605 &self,
606 variables: &task::TaskVariables,
607 ) -> Option<(VariableName, String)> {
608 let python_module_name =
609 python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?);
610
611 let unittest_class_name =
612 variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
613
614 let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
615 "_unittest_method_name",
616 )));
617
618 let unittest_target_str = match (unittest_class_name, unittest_method_name) {
619 (Some(class_name), Some(method_name)) => {
620 format!("{python_module_name}.{class_name}.{method_name}")
621 }
622 (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
623 (None, None) => python_module_name,
624 // should never happen, a TestCase class is the unit of testing
625 (None, Some(_)) => return None,
626 };
627
628 Some((
629 PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
630 unittest_target_str,
631 ))
632 }
633
634 fn build_pytest_target(
635 &self,
636 variables: &task::TaskVariables,
637 ) -> Option<(VariableName, String)> {
638 let file_path = variables.get(&VariableName::RelativeFile)?;
639
640 let pytest_class_name =
641 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
642
643 let pytest_method_name =
644 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
645
646 let pytest_target_str = match (pytest_class_name, pytest_method_name) {
647 (Some(class_name), Some(method_name)) => {
648 format!("{file_path}::{class_name}::{method_name}")
649 }
650 (Some(class_name), None) => {
651 format!("{file_path}::{class_name}")
652 }
653 (None, Some(method_name)) => {
654 format!("{file_path}::{method_name}")
655 }
656 (None, None) => file_path.to_string(),
657 };
658
659 Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
660 }
661
662 fn build_module_target(
663 &self,
664 variables: &task::TaskVariables,
665 ) -> Result<(VariableName, String)> {
666 let python_module_name = python_module_name_from_relative_path(
667 variables.get(&VariableName::RelativeFile).unwrap_or(""),
668 );
669
670 let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
671
672 Ok(module_target)
673 }
674}
675
676fn python_module_name_from_relative_path(relative_path: &str) -> String {
677 let path_with_dots = relative_path.replace('/', ".");
678 path_with_dots
679 .strip_suffix(".py")
680 .unwrap_or(&path_with_dots)
681 .to_string()
682}
683
684fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
685 match k {
686 PythonEnvironmentKind::Conda => "Conda",
687 PythonEnvironmentKind::Pixi => "pixi",
688 PythonEnvironmentKind::Homebrew => "Homebrew",
689 PythonEnvironmentKind::Pyenv => "global (Pyenv)",
690 PythonEnvironmentKind::GlobalPaths => "global",
691 PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
692 PythonEnvironmentKind::Pipenv => "Pipenv",
693 PythonEnvironmentKind::Poetry => "Poetry",
694 PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
695 PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
696 PythonEnvironmentKind::LinuxGlobal => "global",
697 PythonEnvironmentKind::MacXCode => "global (Xcode)",
698 PythonEnvironmentKind::Venv => "venv",
699 PythonEnvironmentKind::VirtualEnv => "virtualenv",
700 PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
701 PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
702 PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
703 }
704}
705
706pub(crate) struct PythonToolchainProvider {
707 term: SharedString,
708}
709
710impl Default for PythonToolchainProvider {
711 fn default() -> Self {
712 Self {
713 term: SharedString::new_static("Virtual Environment"),
714 }
715 }
716}
717
718static ENV_PRIORITY_LIST: &'static [PythonEnvironmentKind] = &[
719 // Prioritize non-Conda environments.
720 PythonEnvironmentKind::Poetry,
721 PythonEnvironmentKind::Pipenv,
722 PythonEnvironmentKind::VirtualEnvWrapper,
723 PythonEnvironmentKind::Venv,
724 PythonEnvironmentKind::VirtualEnv,
725 PythonEnvironmentKind::PyenvVirtualEnv,
726 PythonEnvironmentKind::Pixi,
727 PythonEnvironmentKind::Conda,
728 PythonEnvironmentKind::Pyenv,
729 PythonEnvironmentKind::GlobalPaths,
730 PythonEnvironmentKind::Homebrew,
731];
732
733fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
734 if let Some(kind) = kind {
735 ENV_PRIORITY_LIST
736 .iter()
737 .position(|blessed_env| blessed_env == &kind)
738 .unwrap_or(ENV_PRIORITY_LIST.len())
739 } else {
740 // Unknown toolchains are less useful than non-blessed ones.
741 ENV_PRIORITY_LIST.len() + 1
742 }
743}
744
745/// Return the name of environment declared in <worktree-root/.venv.
746///
747/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
748fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
749 fs::File::open(worktree_root.join(".venv"))
750 .and_then(|file| {
751 let mut venv_name = String::new();
752 io::BufReader::new(file).read_line(&mut venv_name)?;
753 Ok(venv_name.trim().to_string())
754 })
755 .ok()
756}
757
758#[async_trait]
759impl ToolchainLister for PythonToolchainProvider {
760 fn manifest_name(&self) -> language::ManifestName {
761 ManifestName::from(SharedString::new_static("pyproject.toml"))
762 }
763 async fn list(
764 &self,
765 worktree_root: PathBuf,
766 subroot_relative_path: Option<Arc<Path>>,
767 project_env: Option<HashMap<String, String>>,
768 ) -> ToolchainList {
769 let env = project_env.unwrap_or_default();
770 let environment = EnvironmentApi::from_env(&env);
771 let locators = pet::locators::create_locators(
772 Arc::new(pet_conda::Conda::from(&environment)),
773 Arc::new(pet_poetry::Poetry::from(&environment)),
774 &environment,
775 );
776 let mut config = Configuration::default();
777
778 let mut directories = vec![worktree_root.clone()];
779 if let Some(subroot_relative_path) = subroot_relative_path {
780 debug_assert!(subroot_relative_path.is_relative());
781 directories.push(worktree_root.join(subroot_relative_path));
782 }
783
784 config.workspace_directories = Some(directories);
785 for locator in locators.iter() {
786 locator.configure(&config);
787 }
788
789 let reporter = pet_reporter::collect::create_reporter();
790 pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
791
792 let mut toolchains = reporter
793 .environments
794 .lock()
795 .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
796
797 let wr = worktree_root;
798 let wr_venv = get_worktree_venv_declaration(&wr);
799 // Sort detected environments by:
800 // environment name matching activation file (<workdir>/.venv)
801 // environment project dir matching worktree_root
802 // general env priority
803 // environment path matching the CONDA_PREFIX env var
804 // executable path
805 toolchains.sort_by(|lhs, rhs| {
806 // Compare venv names against worktree .venv file
807 let venv_ordering =
808 wr_venv
809 .as_ref()
810 .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
811 (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
812 (Some(l), None) if l == venv => Ordering::Less,
813 (None, Some(r)) if r == venv => Ordering::Greater,
814 _ => Ordering::Equal,
815 });
816
817 // Compare project paths against worktree root
818 let proj_ordering = || match (&lhs.project, &rhs.project) {
819 (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
820 (Some(l), None) if l == &wr => Ordering::Less,
821 (None, Some(r)) if r == &wr => Ordering::Greater,
822 _ => Ordering::Equal,
823 };
824
825 // Compare environment priorities
826 let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
827
828 // Compare conda prefixes
829 let conda_ordering = || {
830 if lhs.kind == Some(PythonEnvironmentKind::Conda) {
831 environment
832 .get_env_var("CONDA_PREFIX".to_string())
833 .map(|conda_prefix| {
834 let is_match = |exe: &Option<PathBuf>| {
835 exe.as_ref().map_or(false, |e| e.starts_with(&conda_prefix))
836 };
837 match (is_match(&lhs.executable), is_match(&rhs.executable)) {
838 (true, false) => Ordering::Less,
839 (false, true) => Ordering::Greater,
840 _ => Ordering::Equal,
841 }
842 })
843 .unwrap_or(Ordering::Equal)
844 } else {
845 Ordering::Equal
846 }
847 };
848
849 // Compare Python executables
850 let exe_ordering = || lhs.executable.cmp(&rhs.executable);
851
852 venv_ordering
853 .then_with(proj_ordering)
854 .then_with(priority_ordering)
855 .then_with(conda_ordering)
856 .then_with(exe_ordering)
857 });
858
859 let mut toolchains: Vec<_> = toolchains
860 .into_iter()
861 .filter_map(|toolchain| {
862 let mut name = String::from("Python");
863 if let Some(ref version) = toolchain.version {
864 _ = write!(name, " {version}");
865 }
866
867 let name_and_kind = match (&toolchain.name, &toolchain.kind) {
868 (Some(name), Some(kind)) => {
869 Some(format!("({name}; {})", python_env_kind_display(kind)))
870 }
871 (Some(name), None) => Some(format!("({name})")),
872 (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
873 (None, None) => None,
874 };
875
876 if let Some(nk) = name_and_kind {
877 _ = write!(name, " {nk}");
878 }
879
880 Some(Toolchain {
881 name: name.into(),
882 path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
883 language_name: LanguageName::new("Python"),
884 as_json: serde_json::to_value(toolchain).ok()?,
885 })
886 })
887 .collect();
888 toolchains.dedup();
889 ToolchainList {
890 toolchains,
891 default: None,
892 groups: Default::default(),
893 }
894 }
895 fn term(&self) -> SharedString {
896 self.term.clone()
897 }
898}
899
900pub struct EnvironmentApi<'a> {
901 global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
902 project_env: &'a HashMap<String, String>,
903 pet_env: pet_core::os_environment::EnvironmentApi,
904}
905
906impl<'a> EnvironmentApi<'a> {
907 pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
908 let paths = project_env
909 .get("PATH")
910 .map(|p| std::env::split_paths(p).collect())
911 .unwrap_or_default();
912
913 EnvironmentApi {
914 global_search_locations: Arc::new(Mutex::new(paths)),
915 project_env,
916 pet_env: pet_core::os_environment::EnvironmentApi::new(),
917 }
918 }
919
920 fn user_home(&self) -> Option<PathBuf> {
921 self.project_env
922 .get("HOME")
923 .or_else(|| self.project_env.get("USERPROFILE"))
924 .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
925 .or_else(|| self.pet_env.get_user_home())
926 }
927}
928
929impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
930 fn get_user_home(&self) -> Option<PathBuf> {
931 self.user_home()
932 }
933
934 fn get_root(&self) -> Option<PathBuf> {
935 None
936 }
937
938 fn get_env_var(&self, key: String) -> Option<String> {
939 self.project_env
940 .get(&key)
941 .cloned()
942 .or_else(|| self.pet_env.get_env_var(key))
943 }
944
945 fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
946 if self.global_search_locations.lock().is_empty() {
947 let mut paths =
948 std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
949 .collect::<Vec<PathBuf>>();
950
951 log::trace!("Env PATH: {:?}", paths);
952 for p in self.pet_env.get_know_global_search_locations() {
953 if !paths.contains(&p) {
954 paths.push(p);
955 }
956 }
957
958 let mut paths = paths
959 .into_iter()
960 .filter(|p| p.exists())
961 .collect::<Vec<PathBuf>>();
962
963 self.global_search_locations.lock().append(&mut paths);
964 }
965 self.global_search_locations.lock().clone()
966 }
967}
968
969pub(crate) struct PyLspAdapter {
970 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
971}
972impl PyLspAdapter {
973 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
974 pub(crate) fn new() -> Self {
975 Self {
976 python_venv_base: OnceCell::new(),
977 }
978 }
979 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
980 let python_path = Self::find_base_python(delegate)
981 .await
982 .context("Could not find Python installation for PyLSP")?;
983 let work_dir = delegate
984 .language_server_download_dir(&Self::SERVER_NAME)
985 .await
986 .context("Could not get working directory for PyLSP")?;
987 let mut path = PathBuf::from(work_dir.as_ref());
988 path.push("pylsp-venv");
989 if !path.exists() {
990 util::command::new_smol_command(python_path)
991 .arg("-m")
992 .arg("venv")
993 .arg("pylsp-venv")
994 .current_dir(work_dir)
995 .spawn()?
996 .output()
997 .await?;
998 }
999
1000 Ok(path.into())
1001 }
1002 // Find "baseline", user python version from which we'll create our own venv.
1003 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1004 for path in ["python3", "python"] {
1005 if let Some(path) = delegate.which(path.as_ref()).await {
1006 return Some(path);
1007 }
1008 }
1009 None
1010 }
1011
1012 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1013 self.python_venv_base
1014 .get_or_init(move || async move {
1015 Self::ensure_venv(delegate)
1016 .await
1017 .map_err(|e| format!("{e}"))
1018 })
1019 .await
1020 .clone()
1021 }
1022}
1023
1024const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1025 "Scripts"
1026} else {
1027 "bin"
1028};
1029
1030#[async_trait(?Send)]
1031impl LspAdapter for PyLspAdapter {
1032 fn name(&self) -> LanguageServerName {
1033 Self::SERVER_NAME.clone()
1034 }
1035
1036 async fn check_if_user_installed(
1037 &self,
1038 delegate: &dyn LspAdapterDelegate,
1039 toolchain: Option<Toolchain>,
1040 _: &AsyncApp,
1041 ) -> Option<LanguageServerBinary> {
1042 if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1043 let env = delegate.shell_env().await;
1044 Some(LanguageServerBinary {
1045 path: pylsp_bin,
1046 env: Some(env),
1047 arguments: vec![],
1048 })
1049 } else {
1050 let venv = toolchain?;
1051 let pylsp_path = Path::new(venv.path.as_ref()).parent()?.join("pylsp");
1052 pylsp_path.exists().then(|| LanguageServerBinary {
1053 path: venv.path.to_string().into(),
1054 arguments: vec![pylsp_path.into()],
1055 env: None,
1056 })
1057 }
1058 }
1059
1060 async fn fetch_latest_server_version(
1061 &self,
1062 _: &dyn LspAdapterDelegate,
1063 ) -> Result<Box<dyn 'static + Any + Send>> {
1064 Ok(Box::new(()) as Box<_>)
1065 }
1066
1067 async fn fetch_server_binary(
1068 &self,
1069 _: Box<dyn 'static + Send + Any>,
1070 _: PathBuf,
1071 delegate: &dyn LspAdapterDelegate,
1072 ) -> Result<LanguageServerBinary> {
1073 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1074 let pip_path = venv.join(BINARY_DIR).join("pip3");
1075 ensure!(
1076 util::command::new_smol_command(pip_path.as_path())
1077 .arg("install")
1078 .arg("python-lsp-server")
1079 .arg("-U")
1080 .output()
1081 .await?
1082 .status
1083 .success(),
1084 "python-lsp-server installation failed"
1085 );
1086 ensure!(
1087 util::command::new_smol_command(pip_path.as_path())
1088 .arg("install")
1089 .arg("python-lsp-server[all]")
1090 .arg("-U")
1091 .output()
1092 .await?
1093 .status
1094 .success(),
1095 "python-lsp-server[all] installation failed"
1096 );
1097 ensure!(
1098 util::command::new_smol_command(pip_path)
1099 .arg("install")
1100 .arg("pylsp-mypy")
1101 .arg("-U")
1102 .output()
1103 .await?
1104 .status
1105 .success(),
1106 "pylsp-mypy installation failed"
1107 );
1108 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1109 Ok(LanguageServerBinary {
1110 path: pylsp,
1111 env: None,
1112 arguments: vec![],
1113 })
1114 }
1115
1116 async fn cached_server_binary(
1117 &self,
1118 _: PathBuf,
1119 delegate: &dyn LspAdapterDelegate,
1120 ) -> Option<LanguageServerBinary> {
1121 let venv = self.base_venv(delegate).await.ok()?;
1122 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1123 Some(LanguageServerBinary {
1124 path: pylsp,
1125 env: None,
1126 arguments: vec![],
1127 })
1128 }
1129
1130 async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1131
1132 async fn label_for_completion(
1133 &self,
1134 item: &lsp::CompletionItem,
1135 language: &Arc<language::Language>,
1136 ) -> Option<language::CodeLabel> {
1137 let label = &item.label;
1138 let grammar = language.grammar()?;
1139 let highlight_id = match item.kind? {
1140 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1141 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1142 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1143 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1144 _ => return None,
1145 };
1146 let filter_range = item
1147 .filter_text
1148 .as_deref()
1149 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1150 .unwrap_or(0..label.len());
1151 Some(language::CodeLabel {
1152 text: label.clone(),
1153 runs: vec![(0..label.len(), highlight_id)],
1154 filter_range,
1155 })
1156 }
1157
1158 async fn label_for_symbol(
1159 &self,
1160 name: &str,
1161 kind: lsp::SymbolKind,
1162 language: &Arc<language::Language>,
1163 ) -> Option<language::CodeLabel> {
1164 let (text, filter_range, display_range) = match kind {
1165 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1166 let text = format!("def {}():\n", name);
1167 let filter_range = 4..4 + name.len();
1168 let display_range = 0..filter_range.end;
1169 (text, filter_range, display_range)
1170 }
1171 lsp::SymbolKind::CLASS => {
1172 let text = format!("class {}:", name);
1173 let filter_range = 6..6 + name.len();
1174 let display_range = 0..filter_range.end;
1175 (text, filter_range, display_range)
1176 }
1177 lsp::SymbolKind::CONSTANT => {
1178 let text = format!("{} = 0", name);
1179 let filter_range = 0..name.len();
1180 let display_range = 0..filter_range.end;
1181 (text, filter_range, display_range)
1182 }
1183 _ => return None,
1184 };
1185
1186 Some(language::CodeLabel {
1187 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1188 text: text[display_range].to_string(),
1189 filter_range,
1190 })
1191 }
1192
1193 async fn workspace_configuration(
1194 self: Arc<Self>,
1195 _: &dyn Fs,
1196 adapter: &Arc<dyn LspAdapterDelegate>,
1197 toolchain: Option<Toolchain>,
1198 cx: &mut AsyncApp,
1199 ) -> Result<Value> {
1200 cx.update(move |cx| {
1201 let mut user_settings =
1202 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1203 .and_then(|s| s.settings.clone())
1204 .unwrap_or_else(|| {
1205 json!({
1206 "plugins": {
1207 "pycodestyle": {"enabled": false},
1208 "rope_autoimport": {"enabled": true, "memory": true},
1209 "pylsp_mypy": {"enabled": false}
1210 },
1211 "rope": {
1212 "ropeFolder": null
1213 },
1214 })
1215 });
1216
1217 // If user did not explicitly modify their python venv, use one from picker.
1218 if let Some(toolchain) = toolchain {
1219 if user_settings.is_null() {
1220 user_settings = Value::Object(serde_json::Map::default());
1221 }
1222 let object = user_settings.as_object_mut().unwrap();
1223 if let Some(python) = object
1224 .entry("plugins")
1225 .or_insert(Value::Object(serde_json::Map::default()))
1226 .as_object_mut()
1227 {
1228 if let Some(jedi) = python
1229 .entry("jedi")
1230 .or_insert(Value::Object(serde_json::Map::default()))
1231 .as_object_mut()
1232 {
1233 jedi.entry("environment".to_string())
1234 .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1235 }
1236 if let Some(pylint) = python
1237 .entry("pylsp_mypy")
1238 .or_insert(Value::Object(serde_json::Map::default()))
1239 .as_object_mut()
1240 {
1241 pylint.entry("overrides".to_string()).or_insert_with(|| {
1242 Value::Array(vec![
1243 Value::String("--python-executable".into()),
1244 Value::String(toolchain.path.into()),
1245 Value::String("--cache-dir=/dev/null".into()),
1246 Value::Bool(true),
1247 ])
1248 });
1249 }
1250 }
1251 }
1252 user_settings = Value::Object(serde_json::Map::from_iter([(
1253 "pylsp".to_string(),
1254 user_settings,
1255 )]));
1256
1257 user_settings
1258 })
1259 }
1260 fn workspace_folders_content(&self) -> WorkspaceFoldersContent {
1261 WorkspaceFoldersContent::WorktreeRoot
1262 }
1263}
1264
1265pub(crate) struct BasedPyrightLspAdapter {
1266 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1267}
1268
1269impl BasedPyrightLspAdapter {
1270 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1271 const BINARY_NAME: &'static str = "basedpyright-langserver";
1272
1273 pub(crate) fn new() -> Self {
1274 Self {
1275 python_venv_base: OnceCell::new(),
1276 }
1277 }
1278
1279 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1280 let python_path = Self::find_base_python(delegate)
1281 .await
1282 .context("Could not find Python installation for basedpyright")?;
1283 let work_dir = delegate
1284 .language_server_download_dir(&Self::SERVER_NAME)
1285 .await
1286 .context("Could not get working directory for basedpyright")?;
1287 let mut path = PathBuf::from(work_dir.as_ref());
1288 path.push("basedpyright-venv");
1289 if !path.exists() {
1290 util::command::new_smol_command(python_path)
1291 .arg("-m")
1292 .arg("venv")
1293 .arg("basedpyright-venv")
1294 .current_dir(work_dir)
1295 .spawn()?
1296 .output()
1297 .await?;
1298 }
1299
1300 Ok(path.into())
1301 }
1302
1303 // Find "baseline", user python version from which we'll create our own venv.
1304 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1305 for path in ["python3", "python"] {
1306 if let Some(path) = delegate.which(path.as_ref()).await {
1307 return Some(path);
1308 }
1309 }
1310 None
1311 }
1312
1313 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1314 self.python_venv_base
1315 .get_or_init(move || async move {
1316 Self::ensure_venv(delegate)
1317 .await
1318 .map_err(|e| format!("{e}"))
1319 })
1320 .await
1321 .clone()
1322 }
1323}
1324
1325#[async_trait(?Send)]
1326impl LspAdapter for BasedPyrightLspAdapter {
1327 fn name(&self) -> LanguageServerName {
1328 Self::SERVER_NAME.clone()
1329 }
1330
1331 async fn initialization_options(
1332 self: Arc<Self>,
1333 _: &dyn Fs,
1334 _: &Arc<dyn LspAdapterDelegate>,
1335 ) -> Result<Option<Value>> {
1336 // Provide minimal initialization options
1337 // Virtual environment configuration will be handled through workspace configuration
1338 Ok(Some(json!({
1339 "python": {
1340 "analysis": {
1341 "autoSearchPaths": true,
1342 "useLibraryCodeForTypes": true,
1343 "autoImportCompletions": true
1344 }
1345 }
1346 })))
1347 }
1348
1349 async fn check_if_user_installed(
1350 &self,
1351 delegate: &dyn LspAdapterDelegate,
1352 toolchain: Option<Toolchain>,
1353 _: &AsyncApp,
1354 ) -> Option<LanguageServerBinary> {
1355 if let Some(bin) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1356 let env = delegate.shell_env().await;
1357 Some(LanguageServerBinary {
1358 path: bin,
1359 env: Some(env),
1360 arguments: vec!["--stdio".into()],
1361 })
1362 } else {
1363 let path = Path::new(toolchain?.path.as_ref())
1364 .parent()?
1365 .join(Self::BINARY_NAME);
1366 path.exists().then(|| LanguageServerBinary {
1367 path,
1368 arguments: vec!["--stdio".into()],
1369 env: None,
1370 })
1371 }
1372 }
1373
1374 async fn fetch_latest_server_version(
1375 &self,
1376 _: &dyn LspAdapterDelegate,
1377 ) -> Result<Box<dyn 'static + Any + Send>> {
1378 Ok(Box::new(()) as Box<_>)
1379 }
1380
1381 async fn fetch_server_binary(
1382 &self,
1383 _latest_version: Box<dyn 'static + Send + Any>,
1384 _container_dir: PathBuf,
1385 delegate: &dyn LspAdapterDelegate,
1386 ) -> Result<LanguageServerBinary> {
1387 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1388 let pip_path = venv.join(BINARY_DIR).join("pip3");
1389 ensure!(
1390 util::command::new_smol_command(pip_path.as_path())
1391 .arg("install")
1392 .arg("basedpyright")
1393 .arg("-U")
1394 .output()
1395 .await?
1396 .status
1397 .success(),
1398 "basedpyright installation failed"
1399 );
1400 let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1401 Ok(LanguageServerBinary {
1402 path: pylsp,
1403 env: None,
1404 arguments: vec!["--stdio".into()],
1405 })
1406 }
1407
1408 async fn cached_server_binary(
1409 &self,
1410 _container_dir: PathBuf,
1411 delegate: &dyn LspAdapterDelegate,
1412 ) -> Option<LanguageServerBinary> {
1413 let venv = self.base_venv(delegate).await.ok()?;
1414 let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1415 Some(LanguageServerBinary {
1416 path: pylsp,
1417 env: None,
1418 arguments: vec!["--stdio".into()],
1419 })
1420 }
1421
1422 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1423 // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
1424 // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
1425 // and `name` is the symbol name itself.
1426 //
1427 // Because the symbol name is included, there generally are not ties when
1428 // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
1429 // into account. Here, we remove the symbol name from the sortText in order
1430 // to allow our own fuzzy score to be used to break ties.
1431 //
1432 // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
1433 for item in items {
1434 let Some(sort_text) = &mut item.sort_text else {
1435 continue;
1436 };
1437 let mut parts = sort_text.split('.');
1438 let Some(first) = parts.next() else { continue };
1439 let Some(second) = parts.next() else { continue };
1440 let Some(_) = parts.next() else { continue };
1441 sort_text.replace_range(first.len() + second.len() + 1.., "");
1442 }
1443 }
1444
1445 async fn label_for_completion(
1446 &self,
1447 item: &lsp::CompletionItem,
1448 language: &Arc<language::Language>,
1449 ) -> Option<language::CodeLabel> {
1450 let label = &item.label;
1451 let grammar = language.grammar()?;
1452 let highlight_id = match item.kind? {
1453 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1454 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1455 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1456 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1457 _ => return None,
1458 };
1459 let filter_range = item
1460 .filter_text
1461 .as_deref()
1462 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1463 .unwrap_or(0..label.len());
1464 Some(language::CodeLabel {
1465 text: label.clone(),
1466 runs: vec![(0..label.len(), highlight_id)],
1467 filter_range,
1468 })
1469 }
1470
1471 async fn label_for_symbol(
1472 &self,
1473 name: &str,
1474 kind: lsp::SymbolKind,
1475 language: &Arc<language::Language>,
1476 ) -> Option<language::CodeLabel> {
1477 let (text, filter_range, display_range) = match kind {
1478 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1479 let text = format!("def {}():\n", name);
1480 let filter_range = 4..4 + name.len();
1481 let display_range = 0..filter_range.end;
1482 (text, filter_range, display_range)
1483 }
1484 lsp::SymbolKind::CLASS => {
1485 let text = format!("class {}:", name);
1486 let filter_range = 6..6 + name.len();
1487 let display_range = 0..filter_range.end;
1488 (text, filter_range, display_range)
1489 }
1490 lsp::SymbolKind::CONSTANT => {
1491 let text = format!("{} = 0", name);
1492 let filter_range = 0..name.len();
1493 let display_range = 0..filter_range.end;
1494 (text, filter_range, display_range)
1495 }
1496 _ => return None,
1497 };
1498
1499 Some(language::CodeLabel {
1500 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1501 text: text[display_range].to_string(),
1502 filter_range,
1503 })
1504 }
1505
1506 async fn workspace_configuration(
1507 self: Arc<Self>,
1508 _: &dyn Fs,
1509 adapter: &Arc<dyn LspAdapterDelegate>,
1510 toolchain: Option<Toolchain>,
1511 cx: &mut AsyncApp,
1512 ) -> Result<Value> {
1513 cx.update(move |cx| {
1514 let mut user_settings =
1515 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1516 .and_then(|s| s.settings.clone())
1517 .unwrap_or_default();
1518
1519 // If we have a detected toolchain, configure Pyright to use it
1520 if let Some(toolchain) = toolchain {
1521 if user_settings.is_null() {
1522 user_settings = Value::Object(serde_json::Map::default());
1523 }
1524 let object = user_settings.as_object_mut().unwrap();
1525
1526 let interpreter_path = toolchain.path.to_string();
1527
1528 // Detect if this is a virtual environment
1529 if let Some(interpreter_dir) = Path::new(&interpreter_path).parent() {
1530 if let Some(venv_dir) = interpreter_dir.parent() {
1531 // Check if this looks like a virtual environment
1532 if venv_dir.join("pyvenv.cfg").exists()
1533 || venv_dir.join("bin/activate").exists()
1534 || venv_dir.join("Scripts/activate.bat").exists()
1535 {
1536 // Set venvPath and venv at the root level
1537 // This matches the format of a pyrightconfig.json file
1538 if let Some(parent) = venv_dir.parent() {
1539 // Use relative path if the venv is inside the workspace
1540 let venv_path = if parent == adapter.worktree_root_path() {
1541 ".".to_string()
1542 } else {
1543 parent.to_string_lossy().into_owned()
1544 };
1545 object.insert("venvPath".to_string(), Value::String(venv_path));
1546 }
1547
1548 if let Some(venv_name) = venv_dir.file_name() {
1549 object.insert(
1550 "venv".to_owned(),
1551 Value::String(venv_name.to_string_lossy().into_owned()),
1552 );
1553 }
1554 }
1555 }
1556 }
1557
1558 // Always set the python interpreter path
1559 // Get or create the python section
1560 let python = object
1561 .entry("python")
1562 .or_insert(Value::Object(serde_json::Map::default()))
1563 .as_object_mut()
1564 .unwrap();
1565
1566 // Set both pythonPath and defaultInterpreterPath for compatibility
1567 python.insert(
1568 "pythonPath".to_owned(),
1569 Value::String(interpreter_path.clone()),
1570 );
1571 python.insert(
1572 "defaultInterpreterPath".to_owned(),
1573 Value::String(interpreter_path),
1574 );
1575 }
1576
1577 user_settings
1578 })
1579 }
1580
1581 fn workspace_folders_content(&self) -> WorkspaceFoldersContent {
1582 WorkspaceFoldersContent::WorktreeRoot
1583 }
1584}
1585
1586#[cfg(test)]
1587mod tests {
1588 use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1589 use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1590 use settings::SettingsStore;
1591 use std::num::NonZeroU32;
1592
1593 #[gpui::test]
1594 async fn test_python_autoindent(cx: &mut TestAppContext) {
1595 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1596 let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1597 cx.update(|cx| {
1598 let test_settings = SettingsStore::test(cx);
1599 cx.set_global(test_settings);
1600 language::init(cx);
1601 cx.update_global::<SettingsStore, _>(|store, cx| {
1602 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1603 s.defaults.tab_size = NonZeroU32::new(2);
1604 });
1605 });
1606 });
1607
1608 cx.new(|cx| {
1609 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1610 let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1611 let ix = buffer.len();
1612 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1613 };
1614
1615 // indent after "def():"
1616 append(&mut buffer, "def a():\n", cx);
1617 assert_eq!(buffer.text(), "def a():\n ");
1618
1619 // preserve indent after blank line
1620 append(&mut buffer, "\n ", cx);
1621 assert_eq!(buffer.text(), "def a():\n \n ");
1622
1623 // indent after "if"
1624 append(&mut buffer, "if a:\n ", cx);
1625 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
1626
1627 // preserve indent after statement
1628 append(&mut buffer, "b()\n", cx);
1629 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
1630
1631 // preserve indent after statement
1632 append(&mut buffer, "else", cx);
1633 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
1634
1635 // dedent "else""
1636 append(&mut buffer, ":", cx);
1637 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
1638
1639 // indent lines after else
1640 append(&mut buffer, "\n", cx);
1641 assert_eq!(
1642 buffer.text(),
1643 "def a():\n \n if a:\n b()\n else:\n "
1644 );
1645
1646 // indent after an open paren. the closing paren is not indented
1647 // because there is another token before it on the same line.
1648 append(&mut buffer, "foo(\n1)", cx);
1649 assert_eq!(
1650 buffer.text(),
1651 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
1652 );
1653
1654 // dedent the closing paren if it is shifted to the beginning of the line
1655 let argument_ix = buffer.text().find('1').unwrap();
1656 buffer.edit(
1657 [(argument_ix..argument_ix + 1, "")],
1658 Some(AutoindentMode::EachLine),
1659 cx,
1660 );
1661 assert_eq!(
1662 buffer.text(),
1663 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
1664 );
1665
1666 // preserve indent after the close paren
1667 append(&mut buffer, "\n", cx);
1668 assert_eq!(
1669 buffer.text(),
1670 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
1671 );
1672
1673 // manually outdent the last line
1674 let end_whitespace_ix = buffer.len() - 4;
1675 buffer.edit(
1676 [(end_whitespace_ix..buffer.len(), "")],
1677 Some(AutoindentMode::EachLine),
1678 cx,
1679 );
1680 assert_eq!(
1681 buffer.text(),
1682 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
1683 );
1684
1685 // preserve the newly reduced indentation on the next newline
1686 append(&mut buffer, "\n", cx);
1687 assert_eq!(
1688 buffer.text(),
1689 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
1690 );
1691
1692 // reset to a simple if statement
1693 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
1694
1695 // dedent "else" on the line after a closing paren
1696 append(&mut buffer, "\n else:\n", cx);
1697 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n ");
1698
1699 buffer
1700 });
1701 }
1702}