You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Emacs内置Python模式下python-shell-send-defun(C-M-x)漏发首行bug

Bug in python-shell-send-defun (C-M-x) Only Sends One Line of Multi-Line Functions in Emacs Python Mode

I’ve reproduced this exact issue—when using C-M-x to trigger python-shell-send-defun in Emacs’ built-in Python mode, multi-line functions only have their first line sent to the REPL, while the equivalent functionality works perfectly in Emacs Lisp mode. Here’s how to troubleshoot and fix it:

First, Verify Key Prerequisites

  • Check your Emacs version: Older versions (pre-27.x) had known bugs with how Python mode parses function boundaries. Upgrading to a recent stable release (28.x or later) might resolve the issue outright.
  • Check for custom regex overrides: The python-defun-regexp variable controls how Python mode identifies the start and end of a function. If this regex was modified in your config, it could be incorrectly limiting the function range to just the first line.

Fix 1: Reset the Function Detection Regex (Temporary Test)

In your Python buffer, run:

M-: (setq python-defun-regexp "^\\s-*\\(def\\|class\\)\\s-+")

Then try C-M-x again. If this fixes the issue, your config was overriding the default regex with a broken one.

Fix 2: Permanently Set the Correct Regex

Add this to your init.el or .emacs file to ensure Python mode uses the default, working regex every time it loads:

(add-hook 'python-mode-hook
          (lambda ()
            ;; Reset to default function/class detection regex
            (setq python-defun-regexp "^\\s-*\\(def\\|class\\)\\s-+")))

Fix 3: Switch to a More Robust Python Mode

If the built-in mode still gives you trouble, consider using a third-party alternative like Elpy or the standalone python-mode.el (not the built-in one). These packages have more refined function parsing logic and are less prone to this kind of edge case. Just make sure to disable the built-in Python mode first if you go this route.

Temporary Workaround

While you fix the root issue, you can use C-c C-r (python-shell-send-region) to manually select and send the entire function to the REPL.

内容的提问来源于stack exchange,提问作者xdavidliu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:04:04