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