python.rs

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