Emacs: How to switch mode after typing certain string? - emacs

I am writing R Markdown (.Rmd) file with a lot of LaTeX contents. The major mode is Markdown-mode. But what I want is that: when I try to type some LaTeX commands between $$, I want to automatically turn on the LaTeX major mode, and after I end the LaTeX chunk with $$ or $, it can turn off LaTeX major mode and turn on Markdown-mode again.
The inline format for LaTeX is
$\alpha$
The equation(displaymath) format for LaTeX is
$$
\alpha + \beta
$$
A similar example is when I was writing a .Rnw file, the major mode is LaTeX, but when I edit the R
code chunk:
<<>>=
y <- 1000
#
between <<>>= and #, it turns on the ESS mode.
So can anyone help me to do the similar stuff in Markdown-LaTeX case? Thanks!
Updates after Inaimathi's answer:
Following http://www.emacswiki.org/emacs/MultipleModes#toc6, I need to modify the two-mode-mode.el
- (if (string= to-mode mode-name)
+ (if (string= to-mode major-mode)
and for emacs 24
- (make-local-hook 'post-command-hook)
Then, by Inaimathi, I put the following in my .emacs:
(require 'two-mode-mode)
(setq default-mode (list "Markdown" 'markdown-mode)
second-modes (list (list "LaTeX" "\\\[" "\\\]" 'latex-mode)))
Then the major mode switches between \[ and \].

If you're ok with your major mode changing as you navigate, two-mode-mode should be able to do what you need. You need to include that .el, then add a block that looks something like
(require 'two-mode-mode)
(setq default-mode (list "Haskell" 'haskell-mode)
second-modes (list (list "Markdown" "\[markdown|" "|\]" 'markdown-mode)))
to your ~/.emacs. The above is what I do to highlight markdown blocks while editing Elm code. For your particular use case, you'd probably need
(require 'two-mode-mode)
(setq default-mode (list "Markdown" 'markdown-mode)
second-modes (list (list "Latex" "\$\$" "\$\$" 'latex-mode)
(list "Latex" "<<>>=" "#" 'latex-mode)))
Instead. This is completely untested, includes no warranty, etc etc.
Ideally, what I'd like in that situation is for the rest of the buffer to keep markdown-mode highlighting, and have just the particular region get highlighted in latex-mode or whatever. Near as I can tell, there isn't a ready, general solution for that, but if you're up for some Elisp hacking, you could give this a read and see what you can come up with.

Related

My Emacs mode does not highlight keywords

I am trying to write an Emacs major mode but it is not working; specifically, my keywords are not being displayed in keyword font face. I have tried to follow the tutorials but I must be doing something wrong. I know a little Lisp but I do not know Emacs scripting.
My Emacs mode script:
;; emacs mode for OldRope
;; does no work for some reason
(setq oldrope-directive-keywords-regexp (regexp-opt '("page" "link" "goto" "act" "end" "div" "span" "include")))
(defvar oldrope-font-lock-defaults '((
(oldrope-directive-keywords-regexp . font-lock-keyword-face))))
(define-derived-mode oldrope-mode fundamental-mode
"oldrope mode"
"Major mode for editing OldRope games"
(setq comment-start "/*")
(setq comment-end "*/")
(setq font-lock-defaults oldrope-font-lock-defaults))
(provide 'oldrope-mode)
Test file:
$[page start]$ Hello $[link]$ Click me $[act]$ That is right. $[end]$
(For context, this is part of https://github.com/martinellison/oldrope but that is not really relevant to the question).
You need this - the rest is OK:
(defvar oldrope-font-lock-defaults
`(((,oldrope-directive-keywords-regexp . font-lock-keyword-face))))
By simply quoting the list you were not evaluating oldrope-directive-keywords-regexp - your quoted list just had that symbol as its car.
Using either backquote (`) plus comma (,) or (list (list (cons oldrope-directive-keywords-regexp 'font-lock-keyword-face))) you evaluate that variable and use its value in the resulting list.

emacs terminal mode: how to copy and paste efficiently

I'm having a hard time making this emacs -nw work effectively under the terminal mode (emacs -nw).
Some setup information:
The working server is connected via SSH, and emacs is running on the server. Usually I'm connecting using SSH and "emacs -nw" to work on my files.
The emacs config is picked up from: https://hugoheden.wordpress.com/2009/03/08/copypaste-with-emacs-in-terminal/
;; make mouse selection to be emacs region marking
(require 'mouse)
(xterm-mouse-mode t)
(defun track-mouse (e))
(setq mouse-sel-mode t)
;; enable clipboard in emacs
(setq x-select-enable-clipboard t)
;; enable copy/paste between emacs and other apps (terminal version of emacs)
(unless window-system
(when (getenv "DISPLAY")
;; Callback for when user cuts
(defun xsel-cut-function (text &optional push)
;; Insert text to temp-buffer, and "send" content to xsel stdin
(with-temp-buffer
(insert text)
;; I prefer using the "clipboard" selection (the one the
;; typically is used by c-c/c-v) before the primary selection
;; (that uses mouse-select/middle-button-click)
(call-process-region (point-min) (point-max) "xsel" nil 0 nil "--clipboard" "--input")))
;; Call back for when user pastes
(defun xsel-paste-function()
;; Find out what is current selection by xsel. If it is different
;; from the top of the kill-ring (car kill-ring), then return
;; it. Else, nil is returned, so whatever is in the top of the
;; kill-ring will be used.
(let ((xsel-output (shell-command-to-string "xsel --clipboard --output")))
(unless (string= (car kill-ring) xsel-output)
xsel-output )))
;; Attach callbacks to hooks
(setq interprogram-cut-function 'xsel-cut-function)
(setq interprogram-paste-function 'xsel-paste-function)
;; Idea from
;; http://shreevatsa.wordpress.com/2006/10/22/emacs-copypaste-and-x/
;; http://www.mail-archive.com/help-gnu-emacs#gnu.org/msg03577.html
))
The reason to have:
(require 'mouse)
(xterm-mouse-mode t)
(defun track-mouse (e))
(setq mouse-sel-mode t)
is to enable mouse selection over text such that the text region is highlighted just as "C-x SPC" marking the region. Then I can use "M-x w" to copy and "C-x y" to paste text within emacs and between emacs and other apps.
All look perfect except that any operations related to X are REALLY SLOW! My connection to the remote server is smooth -- the latency is usually under 100ms. But to kill one line of text using "C-x k", it takes ~5 seconds! To paste it, it takes another 5 seconds!
When copy/paste is frequent sometimes, this becomes really annoying. I think this is related to the X sever messaging, but not sure if there is good way to fix this.
Any ideas?
Thanks!
This is not an ideal solution per se, but i figured out a way that I feel better than the previous one.
The idea is to get rid of X which causes heavy latency issues, i.e. keep only the following:
;; enable clipboard in emacs
(setq x-select-enable-clipboard t)
The results are:
copy/paste within Emacs is straightforward and fast.
copy from other apps to Emacs: Ctrl+Shift+v
copy from Emacs to other apps: mouse selection is now on X Selection, so right-click and copy shall copy the text into the Selection. Note that 'M-w" now won't copy anything into Selection or system clipboard.
This is again a compromise rather than a solution, but considering the fact that i copy/paste more often than inter-app operations, this is acceptable at the moment.
Still looking forward to a good solution!
You can accomplish this by using a terminal escape code!
There is a unique category of terminal escape codes called "Operating System Controls" (OSC) and one of these sequences (\033]52) is meant for interacting with the system clipboard. The great thing is that your terminal doesn't care where the code came from so it will work in remote sessions as well.
Most terminal emulators support it (iTerm2, OS X Terminal, and I think all Linux terminals besides GNOME). You can test if your terminal supports this sequence by simply running:
$ printf "\033]52;c;$(printf "Hello, world" | base64)\a"
Then paste from your system clipboard. If it pastes "Hello, world" then your terminal supports it!
I have this function in my init.el so when I call yank-to-clipboard Emacs will yank the value from my kill ring into the system clipboard:
(defun yank-to-clipboard ()
"Use ANSI OSC 52 escape sequence to attempt clipboard copy"
(interactive)
(send-string-to-terminal
(format "\033]52;c;%s\a"
(base64-encode-string
(encode-coding-string
(substring-no-properties
(nth 0 kill-ring)) 'utf-8) t))))
As I type this, I stumbled upon an almost-identical script supported by Chromium community: https://chromium.googlesource.com/apps/libapps/+/master/hterm/etc/osc52.el
For those running Emacs inside Tmux:
Tmux consumes the sequence, so you'll need to pipe the sequence to the Tmux active tty for this to work. I have a solution in my blog post here: https://justinchips.medium.com/have-vim-emacs-tmux-use-system-clipboard-4c9d901eef40
To extend on #justinokamoto's answer for use in tmux, it works great and is truly amazing. I haven't debugged it with e.g. tramp or other fancy emacs settings but to get it to work
Follow https://sunaku.github.io/tmux-yank-osc52.html great instructions, modifying your tmux.conf and ~/bin/yank
Make sure terminal access to your clipboard is enabled on your terminal
Then to pull into emacs you can use a function like:
(Caveat emptor, I am very new to elisp. This writes to a temporary file in /tmp/yank)
(defun custom-terminal-yank (&rest args)
(message "-> CLIP")
;; FOR EVIL MODE: UNCOMMENT SO FIRST YANKS TO KILL RING
;; need to yank first, with all those args
;; ;; https://emacs.stackexchange.com/questions/19215/how-to-write-a-transparent-pass-through-function-wrapper
;; (interactive (advice-eval-interactive-spec
;; (cadr (interactive-form #'evil-yank))))
;; (apply #'evil-yank args)
;; https://stackoverflow.com/questions/27764059/emacs-terminal-mode-how-to-copy-and-paste-efficiently
;; https://sunaku.github.io/tmux-yank-osc52.html
(f-write-text (nth 0 kill-ring) 'utf-8 "/tmp/yank")
(send-string-to-terminal (shell-command-to-string "~/bin/yank /tmp/yank"))
)
If anyone else uses evil mode as well (just to make things complicated) you can uncomment those lines and use something like
(define-key evil-visual-state-map "Y" 'jonah-terminal-yank)
So that normal "y" is for normal yanking in visual mode, but "Y" is for cross-clipboard yanking

Persistent colors in an emacs text buffer

After highlighting text in an emacs buffer using a regexp (1), it's easy enough to write the setting in the file (2), but I am missing a third step for persistence.
(1) Set
Doing M-s h r (highlight-regexp) and, say, \{.*\} followed by italic will highlight everything between curly braces in that style.
(2) Write
Subsequently calling C-x w b (hi-lock-write-interactive-patterns) will write the string
# Hi-lock: (("\\{.*\\}" (0 (quote italic) t)))
in the buffer, after asking for the comment string (I used #).
(3) Re-use
What is the third step needed to make this highlighting persistent, i.e., to make it survive saving/loading the file from disk?
If you C-h f hi-lock-write-interactive-pattern, you'll see in the help buffer a link to hi-lock.el. Often Lisp libraries have some usage information at the beginning of the file and it's handy to check.
In this case, it tells how to make it persistent:
;; To enable the use of patterns found in files (presumably placed
;; there by hi-lock) include the following in your init file:
;;
;; (setq hi-lock-file-patterns-policy 'ask)
;;
;; If you get tired of being asked each time a file is loaded replace
;; `ask' with a function that returns t if patterns should be read.
How about the possibility of creating a function that has a hook relating to the file you want to load -- e.g., a text-mode-hook or perhaps a specific file hook (if something like that exists)?
;; M-x ae-hi-lock-features
(global-hi-lock-mode 1)
(defface af-bold-yellow-box '((t (:background "black"
:foreground "yellow"
:underline "red"
:height 200
:bold t
))) "yellow-box-face")
(defun z-hi-lock-quizzes ()
;; this next line is necessary to correct sloppy hi-locking
(if (not hi-lock-mode)
(progn (hi-lock-mode -1)
(hi-lock-mode 1))
(hi-lock-mode)
(hi-lock-mode))
(highlight-regexp "^%-\\*-mode:LaTeX.*$" (quote hi-conceal-content));
(highlight-regexp "^%-#-(.+$" (quote hi-lock-page-break));
(highlight-regexp "food" (quote af-bold-yellow-box));
)
(defun ae-hi-lock-features ()
(interactive)
(z-hi-lock-quizzes)
;; ... call other functions ...
)
(add-hook 'text-mode-hook 'ae-hi-lock-features)
https://www.gnu.org/software/emacs/manual/html_node/emacs/Highlight-Interactively.html
C-x w i
Extract regexp/face pairs from comments in the current buffer (hi-lock-find-patterns).
Thus, you can enter patterns interactively
with highlight-regexp, store them into the file with
hi-lock-write-interactive-patterns, edit them (perhaps including
different faces for different parenthesized parts of the match), and
finally use this command (hi-lock-find-patterns) to have Hi Lock
highlight the edited patterns.

Indent code in org-babel src blocks

In an org-mode file, with code like the following:
#+begin_src emacs-lisp
(add-to-list 'org-tab-before-tab-emulation-hook
(lambda ()
(when (within-the-body-of-a-begin-src-block)
(indent-for-tab-command--as-if-in-lisp-mode))))
#+end_src
I would like the TAB key to indent the code as it would if it were in a buffer in lisp mode.
What I need is:
A way to figure out whether the cursor is within a src block. It needs to not trigger when on the header line itself, as in that case the default org folding should take place.
A way to indent the code according to the mode (emacs-lisp in this case) specified in the header.
Org can already syntax highlight src blocks according to mode, and the TAB hooks are there. This looks do-able.
Since Emacs 24.1 you can now set the following option:
(setq org-src-tab-acts-natively t)
...and that should handle all src blocks.
Just move point into the code block and press C-c '
This will pop up a buffer in elisp-mode, syntax higlighting ad all...
Here's a rough solution:
(defun indent-org-src-block-line ()
"Indent the current line of emacs lisp code."
(interactive)
(let ((info (org-babel-get-src-block-info 'light)))
(when info
(let ((lang (nth 0 info)))
(when (string= lang "emacs-lisp")
(let ((indent-line-function 'lisp-indent-line))
(indent-for-tab-command)))))))
(add-to-list 'org-tab-before-tab-emulation-hook
'indent-org-src-block-line)
It only handles emacs-lisp blocks. I've only tested with the src block un-indented (not the org default).
It is tough in general to make one mode work inside another - many keyboard commands will conflict. But some of the more basic strokes, like tab for indent, newline, commenting (org will comment the lisp code with #, which is wrong) seem like they could be made to work and would have the largest impact.
(defun my/org-cleanup ()
(interactive)
(org-edit-special)
(indent-buffer)
(org-edit-src-exit))
should do it, where `indent-buffer' is defined as:
(defun indent-buffer ()
(interactive)
(indent-region (point-min) (point-max)))

Emacs: highlighting TODO *only* in comments

This question is related to another one, Emacs :TODO indicator at left side. I recently came across a minor mode I like a lot called FixmeMode. It supports auto highlighting of TODO marks, and navigating between them. However, I think it makes more sense to recognize the "TODO" strings only in comments, rather than polluting the whole file. Is it possible?
Check out the library fic-mode.el, it has been verified in C++ and Emacs-Lisp.
It was written specifically to answer this question.
The installation is like any standard package:
(require 'fic-mode)
(add-hook 'c++-mode-hook 'turn-on-fic-mode)
Though Wei Hu did ask for an easy way to add it to multiple modes, so here goes:
(defun add-something-to-mode-hooks (mode-list something)
"helper function to add a callback to multiple hooks"
(dolist (mode mode-list)
(add-hook (intern (concat (symbol-name mode) "-mode-hook")) something)))
(add-something-to-mode-hooks '(c++ tcl emacs-lisp) 'turn-on-fic-mode)
It's possible but quite a bit trickier. Fixme mode uses font-lock to do its highlighting, so it works on an as-you-type basis to highlight the keywords. Font-lock hooks in at a very low level, basically running after every change is made to the buffer's contents. It is highly optimized, though, which allows it to appear instantaneous on modern computers.
The TODO indicator in the left fringe is static. Execute the function and all current TODO's are highlighted; change the buffer (adding or removing TODO's) does not change the fringe indicator; that's only changed when the function runs again.
Your approach would have to get into syntax tables, determining first when you're in a comment and then looking for the keywords. The tricky part comes in doing this interactively (i.e. as you type). You should be able to hook into the font-lock constructs to do this, but the function you provide to search for the comment syntax table and then for the keywords better be very efficient, as it will be run each and every time a buffer changes (though it will only run on the changed region, I think). You would want to stuff all of this in font-lock-syntactic-keywords rather than font-lock-keywords because the syntactic-keyword pass happens before the syntactic pass (which happens before the keyword pass), and you need to set TODO inside comments before comments themselves are set.
Sorry it's not a full working-code answer.....
Maybe this will help: there's a fn c-in-literal in
cc-mode, and a similar csharp-in-literal in csharp mode. The
return value is c if in a C-style comment, c++ if in a C++
style comment. You could add that to the code at
Emacs :TODO indicator at left side
to get what you want.
(defun annotate-todo ()
"put fringe marker on TODO: lines in the curent buffer"
(interactive)
(let (lit)
(save-excursion
(goto-char (point-min))
(while (re-search-forward "TODO:" nil t)
(progn
(setq lit (c-in-literal)) ;; or csharp-in-literal
(if (or (eq lit 'c) (eq lit 'c++))
(let ((overlay (make-overlay (- (point) 5) (point))))
(overlay-put overlay 'before-string
(propertize "A"
'display
'(left-fringe ;; right
horizontal-bar
better-fringes-important-bitmap))))))))))
https://github.com/tarsius/hl-todo seems to do exactly what you want. I just tried it and love it.