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