How to highlight floating numbers and integers differently in .F90 files in Emacs? - emacs

How to highlight floating numbers and integers differently in .F90 files in Emacs? In my version 24.4.1, there is no difference between floating numbers and integers. How can I display them in different colors?

The default emacs fortran mode doesn't differentiate the font faces for floats and integers. However, you could use the highlight-numbers package (via M-x package-list-packages or https://github.com/Fanael/highlight-numbers).
Add the following to your .emacs to highlight floats (change the foreground and background colors as you see fit:
(add-hook 'fortran-mode-hook 'highlight-numbers-mode)
(add-hook 'after-init-hook
(lambda ()
(puthash 'fortran-mode
(rx (and symbol-start
(? "-")
(+ digit)
"."
(+ digit)
(*? any)
symbol-end))
highlight-numbers-modelist)
(set-face-attribute 'highlight-numbers-number nil
:foreground "gray60" :background "black")))

I posted this question two weeks ago. Now I have had my own solution. So, I am posting it here as a reference for others who might encountered the same.
First of all, I'd love to thank #Justin for answering before and suggesting the highlight-number-mode. His solution probably works. However, I have a slightly more complicated requirement, so I decided to do it differently.
Also, I'd have to admit that I'm a very beginner in programming. So, you might find some stupid lines in my codes. Feel free to let me know if you think there's a better way.
Here is my solution.
Install highlight-number-mode and parent-mode in emacs. (The second one is required by the first one.) In my case, they are installed under /~/.emcas.d/elpa/.
As far as I see, the original highlight-number-mode does not support f90-mode, and it highlights all numbers (eg. 2, 3.4, 8e-2) equally, by changing fond color. This does not meet my requirement. Specifically, I wish to highlight only floating numbers, and I denoting them either as 2. or .5 in my .f90 script. In Fortran 90, floats and integers have different division rules. So, I hope to visualize them differently in order to reduce the risk of introducing such bugs. Therefore, I changed the following part in the source code (highlight-numbers.el):
(defconst highlight-numbers-generic-regexp
(rx (or
"."
(? (and
symbol-start
digit
symbol-end)
"."
(* digit))))
"Generic regexp for number highlighting.
It is used when no mode-specific one is available.")
(defvar highlight-numbers-modelist
(copy-hash-table
(eval-when-compile
(let ((table (make-hash-table :test 'eq)))
(puthash 'f90-mode
(rx (or
"."
(? (and
symbol-start
(or (and (+ digit) (? (or "." "e" ".e" "E" ".E")) (+ digit))
(and (+ digit) (? (or "e-" ".e-" "E-" ".E-")) (+ digit))
(and (+ digit) "." (+ digit) (? (or "e" "E")) (+ digit))
(* digit))
symbol-end)
"."
(* digit))))
table)
If you compare the above code with the original one by Fanael Linithien, you will notice that I have added two ".". As Fanael said (in private discussions), this is probably due to that "." is taken as a punctuation in f90-mode in emacs. So, I have to modify the regexp and the table accordingly.
Once the above has been done, I put the line (add-hook 'f90-mode-hook 'highlight-numbers-mode) in my init.el to load this package via elpa.
Afterwards, the floats in my code will be highlighted, such as
example
And you can see the difference in floats and integers.
In the end, I'd add that I have been using this for quite a few days. No problems happen so far. So, I guess it is working! :)

Related

Emacs-lisp: prettify-symbols-mode for LaTeX

I was trying to port over the "pretty entities" behaviour from org-mode to latex-mode using the Emacs builtin prettify-symbols-mode. This mode uses font-lock-mode to display character sequences in a buffer as a single (unicode) character. By default for instance emacs-lisp code
(lambda () t)
becomes
(λ () t)
It does however seem to require the character sequences to be separated by some characters, e.g. white-spaces. For instance in my setup, the replacement
\alpha \beta -> α β`
will work, but it will fail when the strings are not separated, e.g.
\alpha\beta -> \alphaβ
This is an issue specifically, because I wanted to use this prettification to make quantum mechanical equations more readable, where I e.g. the replacement like
|\psi\rangle -> |ψ⟩
Is it possible to avoid this delimiter-issue using prettify-symbols-mode? And if it is not, is it possible by using font-lock-mode on a lower level?
Here's the code that should do what you want:
(defvar pretty-alist
(cl-pairlis '("alpha" "beta" "gamma" "delta" "epsilon" "zeta" "eta"
"theta" "iota" "kappa" "lambda" "mu" "nu" "xi"
"omicron" "pi" "rho" "sigma_final" "sigma" "tau"
"upsilon" "phi" "chi" "psi" "omega")
(mapcar
(lambda (x) (make-char 'greek-iso8859-7 x))
(number-sequence 97 121))))
(add-to-list 'pretty-alist '("rangle" . ?\⟩))
(defun pretty-things ()
(mapc
(lambda (x)
(let ((word (car x))
(char (cdr x)))
(font-lock-add-keywords
nil
`((,(concat "\\(^\\|[^a-zA-Z0-9]\\)\\(" word "\\)[a-zA-Z]")
(0 (progn
(decompose-region (match-beginning 2) (match-end 2))
nil)))))
(font-lock-add-keywords
nil
`((,(concat "\\(^\\|[^a-zA-Z0-9]\\)\\(" word "\\)[^a-zA-Z]")
(0 (progn
(compose-region (1- (match-beginning 2)) (match-end 2)
,char)
nil)))))))
pretty-alist))
As you can see above, pretty-alist starts out with greek chars. Then I add
\rangle just to demonstrate how to add new things.
To enable it automatically, add it to the hook:
(add-hook 'LaTeX-mode-hook 'pretty-things)
I used the code from here as a starting
point, you can look there for a reference.
The code of prettify-symbols-mode derives from code developped for languages like Haskell and a few others, which don't use something like TeX's \. So you may indeed be in trouble. I suggest you M-x report-emacs-bug requesting prettify-symbol-mode be improved to support TeX-style syntax.
In the mean time, you'll have to "do it by hand" along the lines of what abo-abo suggests.
One note, tho: back in the days of Emacs-21, I ported X-Symbol to work on Emacs, specifically because I wanted to see such pretty things in LaTeX. Yet, I discovered that it was mostly useless to me. And I think it's even more the case now. Here's why:
You can just use an actual ψ character in your LaTeX code instead of \psi nowadays. So you don't need display tricks for it to look "right".
Rather than repeating |\psi\rangle I much prefer defining macros and then use \Qr{\Vangle} (where \Vangle turns into \psi ("V" stands for "metaVariable"), and \Qr wraps it in a braket) so I can easily tweak those macros and know that the document will stay consistent. At that point, pretty-display of \psi and \rangle is of no importance.

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 " "))))

How to check if symbol is T?

I am doing some text processing, part of it is splitting words into single characters. Every character gets interned as a symbol in upper case with some frequency value assigned to it just for the sake of easiness but as one might imagine, there is a stumbling block in form of the T constant.
The solution I am looking at now is to simply use a lowercase symbol instead of upper case T, however I am wondering if there would be a quick and easy way to verify if the symbol at hand is T.
All I can think of is:
(intern (if (string= "T" (symbol-name symbol)) #\t symbol)
but that just does not look nice since string comparison is not cumbersome. Any ideas?
PS. I need all the symbols in upper case since it is less hassle to evaluate them in listener but I can live with one lowercase t.
You should use a hash table instead of hacking the current package into an ad-hoc one. It sidesteps the T issue entirely, and is a far cleaner solution.
If concision is a concern, you can have a function like (defun frequency (char) (gethash char the-table)), which you ought to use even in the main body of code, since aside from being shorter it means your code is written in terms of "frequencies of characters" rather than in terms of "looking up values in a hash table."
If you're looking for the ultimate in keyboarding minimalism for the REPL, you can go so far as to define a reader macro such as:
(set-macro-character #\?
(lambda (stream char)
(declare (ignore char))
(let ((char (read stream)))
`(frequency (character ',char))))
t)
Which I guess you might not understand wholly, but nevertheless you can inspect the frequency of #\A with something as simple as ?A.
Anyways, the point is to write code that accomplishes its objectives simply, perspicuously, and aligned to good style and "best practises," because if you desire something special-purpose like less-typing-in-the-REPL you can always pile on another abstraction layer.
You may shadow the symbol T:
CL-USER> (shadow 't)
COMMON-LISP:T
CL-USER> (let ((t 17)) t)
17
The shadowed constant T may still be referred to as cl:t.

How do I get emacs to indent other things like it indents define?

So Emacs is pretty good at editing Scheme/Racket/Lisp code. One good thing it does is when you type code like:
(define (make-position-table)
(for/list ([i (in-range 256)])
`()))
It does a very clever thing and indents the second line to two columns. Now the third line it does what it does with all lisp code and indents that to align all the arguments.
How do I customize Emacs so that it indents the third line as though I was introducing a new body. What I'd like is:
(define (make-position-table)
(for/list ([i (in-range 256)])
`()))
I'm guessing this is possible and that I just haven't figured out the arcane Emacs variable to set. Does anyone know how to do this?
You can add this to your .emacs file:
(put 'for/list 'scheme-indent-function 1)
See also a hacked version of scheme mode that does many more racket-isms.
I believe (put 'for/list 'scheme-indent-function 'defun) should do what you want.
Repeat for other symbols. My .emacs includes
(mapc (lambda (sym) (put sym 'scheme-indent-function 'defun))
(list 'for 'for/list 'for/and 'for/or
'match 'case 'syntax-parse 'test-suite 'test-case
'define-syntax-rule 'match-let 'match-let*))
from the days when I was dabbling in PLT Scheme.