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