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