views:

218

answers:

3

I'm editing some Python code with rather long functions and decided it would be useful to quickly get the function name without scrolling up. I put this bit of code together to do it. Is there something built in to emacs in general, or the standard python mode in particular, which I can use instead?

(defun python-show-function-name()
  "Message the name of the function the point is in"
  (interactive)
  (save-excursion
    (beginning-of-defun)
    (message (format "%s" (thing-at-point 'line)))))
A: 

C-c C-u (py-goto-block-up) might be what you want.

Jarret Hardie
Unfortunately, this requires moving in the buffer, which may not be what poster wants...
Blair Conrad
That's where save-excursion comes in.
Ryan Thompson
+14  A: 

You may find decent results with which-function-mode:

Which Function mode is a minor mode that displays the current function name in the mode line, updating it as you move around in a buffer.

To either enable or disable Which Function mode, use the command M-x which-function-mode. This command is global; it applies to all buffers, both existing ones and those yet to be created. However, it takes effect only in certain major modes, those listed in the value of which-func-modes. If the value is t, then Which Function mode applies to all major modes that know how to support it—in other words, all the major modes that support Imenu.

Although I see it getting a little confused in one Python file that I have here...

Blair Conrad
Yes, and this works not only for python
Alex Ott
Thanks, that's ideal. It looks like it mostly works in python-mode although it reports the class you're working in rather than the function, and you have to enable it, as it's not in 'which-func-modes' by default.
justinhj
+2  A: 

Did you try py-beginning-of-def-or-class?

(defun python-show-function-name()
  "Message the name of the function the point is in"
  (interactive)
  (save-excursion
    (py-beginning-of-def-or-class)
    (message (format "%s" (thing-at-point 'line)))))

I find it gives me better results than your beginning-of-defun, but if that's not the problem you're having, then maybe I'm just seeing another symptom of the cause of the wonkiness in my other answer.

Blair Conrad
I might try that but so far it works for every function.
justinhj