Emacs内置Python模式下python-shell-send-defun(C-M-x)漏发首行bug
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-regexpvariable 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

