Color variables inside parenthesis - emacs

I recently transitioned from vim to emacs and miss one key feature of shell scripting: variables being highlighted inside double quotes. How do I put this feature back in?
I read in another thread that you can use syntax-ppss to detect interior of quotes, but how do I actually change the color?
Note that the colors should be turned on for: name="$first $last" but NOT for name='$first $last'

Interestingly, this exact question was asked and answered in emacs.stackexchange.com just a couple of days ago:
The code below use a font-lock rule with a function instead of a regexp, the function search for occurrences of $VAR but only when they are inside a double-quoted string. The function (syntax-ppss) is used to determine this.
The font-lock rule use the prepend flag to add itself on top of the existing string highlighting. (Note that many packages use t for this. Unfortunately, this overwrites all aspects of the existing highlighting. For example, using prepend will retain a string background color (if there is one) while replacing the foreground color.)
(defun sh-script-extra-font-lock-is-in-double-quoted-string ()
"Non-nil if point in inside a double-quoted string."
(let ((state (syntax-ppss)))
(eq (nth 3 state) ?\")))
(defun sh-script-extra-font-lock-match-var-in-double-quoted-string (limit)
"Search for variables in double-quoted strings."
(let (res)
(while
(and (setq res
(re-search-forward
"\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?#!]\\)"
limit t))
(not (sh-script-extra-font-lock-is-in-double-quoted-string))))
res))
(defvar sh-script-extra-font-lock-keywords
'((sh-script-extra-font-lock-match-var-in-double-quoted-string
(2 font-lock-variable-name-face prepend))))
(defun sh-script-extra-font-lock-activate ()
(interactive)
(font-lock-add-keywords nil sh-script-extra-font-lock-keywords)
(if (fboundp 'font-lock-flush)
(font-lock-flush)
(when font-lock-mode
(with-no-warnings
(font-lock-fontify-buffer)))))
You can call use this by adding the last function to a suitable hook, for example:
(add-hook 'sh-mode-hook 'sh-script-extra-font-lock-activate)

Related

How to never expand yasnippets in comments and strings

I'd like to disable YASnippet expansion (for example, if) in comments and strings, but don't find how to do that in a generic way.
On The condition system, they say how to do it for Python, but I'd like to get it working for all prog-modes at once, and I'm not aware of any function which tests "in string/comment", independently of the language.
Is there still a way to do so?
Using lawlist's suggestion and adding it to prog-mode-hook:
(defun yas-no-expand-in-comment/string ()
(setq yas-buffer-local-condition
'(if (nth 8 (syntax-ppss)) ;; non-nil if in a string or comment
'(require-snippet-condition . force-in-comment)
t)))
(add-hook 'prog-mode-hook 'yas-no-expand-in-comment/string)

How do I font lock dollar signs (math mode delimiters) in AUCTeX buffer only outside comments?

I wrote the following code to highlight dollar signs in AUCTeX buffers in different colors, but then I found that it's even highlighting dollar signs in comments, which was unintended, but I am starting to like it. But now just for curiosity, I wonder if that can be avoided.
(defun my-LaTeX-mode-dollars ()
(font-lock-add-keywords
nil
`((,(rx "$") (0 'success t)))
t))
(add-hook 'LaTeX-mode-hook 'my-LaTeX-mode-dollars)
From the documentation of font-lock-keywords:
MATCH-HIGHLIGHT should be of the form:
(SUBEXP FACENAME [OVERRIDE [LAXMATCH]])
OVERRIDE and LAXMATCH are flags. If OVERRIDE is t, existing
fontification can be overwritten. If keep', only parts not already
fontified are highlighted. Ifprepend' or `append', existing
fontification is merged with the new, in which the new or existing
fontification, respectively, takes precedence.
In other words, if you drop the t after 'success, it will no longer fontify dollar signs in comments and strings.
EDIT:
Apparently, the above solution is not sufficient in this situation, probably because dollar signs have been colored using another face earlier.
One way that might work is to not pass the HOW parameter (currently t) to font-lock-add-keywords. This means that they should be added to the end of the list. However, this might cause other things to stop working.
If we need a bigger hammer, you can write a bit more advanced rule that inspects the current fontification, and decides what to do upon this. For example, the following is used by Emacs to add a warning face to parentheses placed at column 0 in strings:
"^\\s("
(0
(if
(memq
(get-text-property
(match-beginning 0)
'face)
'(font-lock-string-face font-lock-doc-face font-lock-comment-face))
(list 'face font-lock-warning-face 'help-echo "Looks like a toplevel defun: escape the parenthesis"))
prepend)
A third way to do this is to replace the regexp (rx "$") with the name of function that could search for $ and check that it appears in the correct context. One example of such font-lock rules can be found in the standard Emacs package cwarn.

How to make the tilde overwrite a space in Emacs?

I'd like (in TeX-related modes) the tilde key to insert itself as usual if point is on anything (in particular a line end), but if a point is on space, I'd like the tilde to overwrite it. (This would be a quite useful feature after pasting something into TeX source file.) I hacked something like this:
(defun electric-tie ()
"Inserts a tilde at point unless the point is at a space
character, in which case it deletes the space first."
(interactive)
(while (equal (char-after) 32) (delete-char 1))
(while (equal (char-before) 32) (delete-char -1))
(insert "~"))
(add-hook 'TeX-mode-hook (lambda () (local-set-key "~" 'electric-tie)))
My questions are simple: is it correct (it seems to work) and can it be done better? (I assume that if the answer to the first question is in the affirmative, the latter is a question of style.)
As mentioned, it's better to use a "character" literal than a number literal. You have the choice between ? , ?\ , and ?\s where the last one is only supported since Emacs-22 but is otherwise the recommended way, since it's (as you say) "more easily visible" and also there' no risk that the space char will be turned into something else (or removed) by things like fill-paragraph or whitespace trimming.
You can indeed use eq instead of equal, but the difference is not important.
Finally, I'd call (call-interactively 'self-insert-command) rather than insert by hand, but the difference is not that important (e.g. it'll let you insert 3 tildes with C-u ~).
Some points:
Instead of 32 use ?  (question-mark space) to express character literal.
Instead of defining keys in the major-mode hooks, do it in an eval-after-load block. The difference is that major-mode hook runs every time you use the major-mode, but there is only one keymap per major-mode. So there is no point in repeatedly redefining a key in it.
see: https://stackoverflow.com/a/8139587/903943
It looks like this command should not take a numeric argument, but it's worth understanding interactive specs to know how other commands you write can be made to be more flexible by taking numeric arguments into consideration.
One more note about your new modifications:
Your way to clear spaces around point is not wrong, but I'd do this:
(defun foo ()
(interactive)
(skip-chars-forward " ")
(delete-region (point) (+ (point) (skip-chars-backward " "))))

Emacs Auctex custom syntax highlight

I'd like to highlight a new command I created in LaTeX:
\newcommand{\conceito}[3]{
\subsection{#1} (Original: \textit{#2} #3).
}
I use this code in this way:
\conceito{Foo}{Bar}{Bla}
I followed the manual and put this code in my ~/.emacs, but it didn't work:
(add-hook 'LaTeX-mode-hook
(lambda ()
(font-lock-add-keywords nil
'((""\\<\\(\\conceito)\\>"" 1 font-lock-warning-face t)))))
What's wrong?
EDIT: Deokhwan Kim originally pointed out that your regexp contains two consecutive double quotes, and that the closing parenthesis ) needs to be escaped with double quotes as well:
(add-hook 'LaTeX-mode-hook
(lambda ()
(font-lock-add-keywords nil
'(("\\<\\(\\conceito\\)\\>" 1 font-lock-warning-face t)))))
In addition to the points pointed out by Deokhwan Kim, there are also the following two issues:
You need four backslashs instead of two in front of 'conceito': \\\\conceito
The backslash sequence \\< matches the empty string only at the beginning of a word, however, the backslash at the beginning of your new LaTeX command is not considered part of a word, so \\< will not match.
Try this instead:
(add-hook 'LaTeX-mode-hook
(lambda ()
(font-lock-add-keywords nil
'(("\\(\\\\conceito\\)\\>" 1 font-lock-warning-face t)))
EDIT: Another good observation that Deokhwan Kim made is that in this particular case, you don't really need the parenthesis at all, because you're attempting to match the whole expression anyway. So an alternative to the last line could be:
'(("\\\\conceito\\>" 0 font-lock-warning-face t)))))
The point about the parenthesis is correct, but you could actually extend your regexp to only match when an opening curly brace { follows the word "conceito". But since you don't really want to highlight that brace, using sub-groups defined by parentheses is the way to go:
(add-hook 'LaTeX-mode-hook
(lambda ()
(font-lock-add-keywords nil
'(("\\(\\\\conceito\\)\\s-*{" 1 font-lock-warning-face t)))
Note that since we're testing for a { that follows directly after "conceito" (unless there's whitespace in between), we don't need the test for \\> any more at all.
In general, try M-x re-builder to craft regular expression interactively: you can edit a new regexp in a small buffer and instantly see what is highlighted in the buffer from which you invoked the re-builder.
GNU AUCTeX has a built-in way of defining custom highlighting to user-defined macros. Have a look at the variable font-latex-user-keyword-classes and the AUCTeX documentation.
Here's a simple example (my configuration):
(setq font-latex-user-keyword-classes
'(("shadow-hidden" (("hide" "{")) shadow command)
("shadow-mycomment" (("mycomment" "{")) shadow command)
("shadow-comment" (("comment" "{")) shadow command)))
This will show the contents of \hide{}, \mycomment{}, and \comment{} macros in the dim shadow face.

Overload a Keybinding in Emacs

I've looked through a number of other questions and el files looking for something i could modify to suit my needs but I'm having trouble so I came to the experts.
Is there anyway to have a key behave differently depending on where in the line the cursor is?
To be more specific I'd like to map the tab key to go to the end of the line if I'm in the middle of the line but work as a tab normally would if my cursor is positioned at the beginning of the line.
So far I have braces and quotes auto-pairing and re-positioning the cursor within them for C++/Java etc. I'd like to use the tab key to end-of-line if for example a function doesn't have any arguments.
Behaving differently depending on where point is in the line is the easy bit (see (if (looking-back "^") ...) in the code). "[Working] as a tab normally would" is the harder bit, as that's contextual.
Here's one approach, but I was thinking afterwards that a more robust method would be to define a minor mode with its own binding for TAB and let that function look up the fallback binding dynamically. I wasn't sure how to do that last bit, but there's a solution right here:
Emacs key binding fallback
(defvar my-major-mode-tab-function-alist nil)
(defmacro make-my-tab-function ()
"Return a major mode-specific function suitable for binding to TAB.
Performs the original TAB behaviour when point is at the beginning of
a line, and moves point to the end of the line otherwise."
;; If we have already defined a custom function for this mode,
;; return that (otherwise that would be our fall-back function).
(or (cdr (assq major-mode my-major-mode-tab-function-alist))
;; Otherwise find the current binding for this mode, and
;; specify it as the fall-back for our custom function.
(let ((original-tab-function (key-binding (kbd "TAB") t)))
`(let ((new-tab-function
(lambda ()
(interactive)
(if (looking-back "^") ;; point is at bol
(,original-tab-function)
(move-end-of-line nil)))))
(add-to-list 'my-major-mode-tab-function-alist
(cons ',major-mode new-tab-function))
new-tab-function))))
(add-hook
'java-mode-hook
(lambda () (local-set-key (kbd "TAB") (make-my-tab-function)))
t) ;; Append, so that we run after the other hooks.
This page of Emacs Wiki lists several packages (smarttab, etc.) which make TAB do different things depending on the context. You can probably modify one of them to do what you want.