help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Enabling mode for part of buffer / region


From: Michael Anckaert
Subject: Re: Enabling mode for part of buffer / region
Date: Fri, 24 Jan 2020 11:49:57 +0100
User-agent: mu4e 1.1.0; emacs 26.3

I wanted to document my problem and the solution I reached in case some
else needs it. 

After some more searching (Thanks to Drew's reply I got pointed in the
direction of narrowing) I came up with a fairly simple and useful
solution. 

What I want to accomplish is to edit part of a buffer in a different
mode than the buffer currently is. My biggest use case today is editing
a piece of code in an email. I compose my emails using Emacs and mu4e,
so my email buffer is in mu4e-compose-mode. But if I want to edit a
piece of lisp inside that buffer, I want to be able to take advantage of
lisp-mode.

The solution below enables me to narrow to a region and start a mode of
choice. When widening the previous buffer mode is restored.

Thanks to Drew and the folks on #Emacs for their pointers!

;;;; Narrow Edit Mode - NAD
;;;; Load the following elisp code in your Emacs. Run the function 
nad-edit-region to narrow the buffer to the marked region and switch to the 
mode you specified. After widening the buffer will restore to the previous mode.

(defvar *nad-saved-mode* nil)

(defun nad-store-mode (&rest args)
  "Hook to add before narrow. Stores the current mode so we can restore it 
later"
  (setf *nad-saved-mode* major-mode)
  (message "Stored mode: %s" *nad-saved-mode*))

(defun nad-restore-mode (&rest args)
  "hook to add after widen. Restores the saved mode"
  (message "Restoring mode to %s" *nad-saved-mode*)
  (funcall *nad-saved-mode*))

(defun nad-edit-region (mode)
  "Function that prompts for the requested mode and narrows the buffer to 
better edit the current region"
  (interactive "sMode to edit region in: ")
  (narrow-to-region (mark) (point))
  (message "Setting mode to %s" mode)
  (funcall (intern mode)))

(advice-add 'narrow-to-region :before #'nad-store-mode)
(advice-add 'widen :after #'nad-restore-mode)

Michael Anckaert writes:

> Hello everyone,
>
> I'm sure I'm missing something obvious but I wondered if I can enable a
> mode for part of a buffer.
>
> Suppose I'm writing an email and would like to enable python-mode in
> the email, but only for a selected part.
> Is this possible in Emacs? 
>
> Kind regards


-- 
Michael Anckaert
+32 474 066 467
https://www.sinax.be



reply via email to

[Prev in Thread] Current Thread [Next in Thread]