bug#41784: 26.3; Narrow to prompt (narrow-to-defun fro M-x shell / comint)

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

bug#41784: 26.3; Narrow to prompt (narrow-to-defun fro M-x shell / comint)

Pierre Neidhardt-2
Hi!

I like the narrow-to-defun command and I miss it for comint-mode / M-x shell.
Besides, I found it quite hard to reliably parse prompts, especially
multiline prompt.

So here are a bunch of functions that I think would make a great
addition to upstream :)

--8<---------------cut here---------------start------------->8---
(defun ambrevar/shell-prompt-begin-position ()
  ;; We need this convoluted function because `looking-at-p' does not work on
  ;; multiline regexps _and_ `re-search-backward' skips the current line.
  (save-excursion
    (let ((old-point (point)))
      (max
       (save-excursion
         ;; Right result if not on prompt.
         (call-interactively #'comint-previous-prompt)
         (re-search-backward comint-prompt-regexp)
         (point))
       (save-excursion
         ;; Right result if on first char after prompt.
         (re-search-backward comint-prompt-regexp)
         (point))
       (save-excursion
         ;; Right result if on prompt.
         (call-interactively #'comint-next-prompt)
         (re-search-backward comint-prompt-regexp)
         (if (<= (point) old-point)
             (point)
           (point-min)))))))

(defun ambrevar/shell-prompt-end-position ()
  (save-excursion
    (goto-char (ambrevar/shell-prompt-begin-position))
    (call-interactively #'comint-next-prompt)
    (point)))

(defun ambrevar/shell-prompt ()
  (buffer-substring-no-properties
   (ambrevar/shell-prompt-begin-position)
   (ambrevar/shell-prompt-end-position)))

(defun ambrevar/shell-narrow-to-prompt ()
  "Narrow buffer to prompt at point."
  (interactive)
  (let ((begin (ambrevar/shell-prompt-begin-position)))
    (narrow-to-region
     begin
     (save-excursion
       (goto-char (ambrevar/shell-prompt-end-position))
       (call-interactively #'comint-next-prompt)
       (if (= begin
              (ambrevar/shell-prompt-begin-position))
           (point-max)
         (ambrevar/shell-prompt-begin-position))))))

(define-key shell-mode-map (kbd "C-x n d") 'ambrevar/shell-narrow-to-prompt)
--8<---------------cut here---------------end--------------->8---

Cheers!

--
Pierre Neidhardt
https://ambrevar.xyz/

signature.asc (497 bytes) Download Attachment
Reply | Threaded
Open this post in threaded view
|

bug#41784: 26.3; Narrow to prompt (narrow-to-defun fro M-x shell / comint)

Pierre Neidhardt-2
Thanks a lot!

--
Pierre Neidhardt
https://ambrevar.xyz/

signature.asc (521 bytes) Download Attachment