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