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