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