5

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:

http://blogs.fluidinfo.com/terry/2011/01/28/py-narrow-to-class/

5

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.

4

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 ()
    (interactive)
    (save-excursion
        (python-nav-beginning-of-block)
        (let ((last-point nil))
            (while (or (null last-point) (/= (point) last-point))
                (setq last-point (point))
                (python-nav-backward-up-list)))
        (forward-line)
        (narrow-to-defun)))

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))
        erg)
    (save-excursion
    (back-to-indentation)
    (python-nav-forward-statement)
    (python-nav-backward-statement)
    (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))
    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 ()
    (interactive)
    (save-excursion
        (python-nav-beginning-of-block)
        (while (not (my/py-statement-opens-class-p))
            (python-nav-backward-up-list))
        (forward-line)
        (narrow-to-defun)))
1
   (defun py-narrow-to-class ()
      "Make text outside current class invisible. "
      (interactive)
      (save-excursion
        (let ((start (if (py--statement-opens-class-p)
                         (point)
                       (py-beginning-of-class))))
          (py-end-of-class)
          (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.