简体   繁体   中英

Open selection in different major mode.

Is it possible to select some parts of a text and open it in a different buffer with a different mode?

Fore example, if I often work in ESS mode (syntax highlighting for R),

astring <- '<form>
<input type="checkbox" id="foo", value="bar">
</form>'

if the text within the single quotes is selected, I would like to edit it in a new buffer HTML mode (similar to org-src-lang-modes in orgmode ).

What you're describing is called an 'indirect buffer'. You create one by calling Mx clone-indirect-buffer . This creates a second copy of the buffer you're editing. Any changes made in one buffer are mirrored in the other. However, both buffers can have different major modes active, so one can be in ESS mode, and the other in HTML (or whatever you like).

See the manual for details.

Here is one method of handling the issue using narrow-to-region -- the example contemplates that the point (cursor) will be somewhere between the single quotes when typing Mx narrow-to-single-quotes . A simple two-line function can be used to exit -- (widen) (ess-mode) ; or, you can get fancy with recursive-edit . Of course, this is not the same as opening the text in a new buffer. A similar functionality can also be used to copy the region to a new buffer, but I am assuming that the original poster may want to incorporate the edited text back into the primary buffer.

(defun narrow-to-single-quotes ()
"When cursor (aka point) is between single quotes, this function will narrow
the region to whatever is between the single quotes, and then change the
major mode to `html-mode`.  To exit, just type `M-x widen` and then
`M-x [whatever-previous-major-mode-was-used]`."
(interactive)
  (let* (
      (init-pos (point))
      beg
      end)
    (re-search-backward "'" nil t)
    (forward-char 1)
    (setq beg (point))
    (re-search-forward "'" nil t)
    (backward-char 1)
    (setq end (point))
    (narrow-to-region beg end)
    (html-mode)
    (goto-char init-pos)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM