How can I narrow a buffer to the python class at point?

narrow-to-region works but requires first selecting the class as a region, and it seems python-mode has moved on since this was written:



Move the cursor the the top of the class and use narrow-to-defun. You can reach the top of the class by using python-nav-backward-up-list.


With erikstokes' answer, I was able to write this, which uses python.el to narrow to the outermost scope regardless of where point is in the class:

(defun my/python-narrow-to-outer-scope ()
        (let ((last-point nil))
            (while (or (null last-point) (/= (point) last-point))
                (setq last-point (point))

Or more specifically narrowing to the 'nearest' opening class definition (nearest moving up the hierarchy of class/def nesting from point):

(defun my/py-statement-opens-base (regexp)
(let ((orig (point))
    (when (and
            (<= (line-beginning-position) orig)(looking-back "^[ \t]*" (line-beginning-position))(looking-at regexp))
        (setq erg (point))))
    (when (called-interactively-p 'any) (message "%s" erg))

(defconst my/py-class-re "[ \t]*\\_<\\(class\\)\\_>[ \n\t]"
"Matches the beginning of a class definition. ")

(defun my/py-statement-opens-class-p ()
"Return `t' if the statement opens a functions or class definition, nil otherwise. "
    (my/py-statement-opens-base my/py-class-re))

(defun my/python-narrow-to-class ()
        (while (not (my/py-statement-opens-class-p))
   (defun py-narrow-to-class ()
      "Make text outside current class invisible. "
        (let ((start (if (py--statement-opens-class-p)
          (narrow-to-region (point) start))))

Meanwhile narrowing of basic forms like this --or block, statement etc.-- is implemented in python-mode.el.

  • I think this depends on python-model.el as opposed to python.el. I'm using the latter because it comes with emacs. – Croad Langshan Feb 8 '17 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.