In source code, I'd like to display “-” as “−”. In the font I use, the dash is very short and doesn't match the “+” at all. This is only to improve visual appearance. The character in the file must remain the same because it is code, which need to stay correct.

So far, I've used:

(add-hook 'python-mode-hook
          (lambda ()
            (font-lock-add-keywords nil
                                       (0 (progn (compose-region (match-beginning 0) (match-end 0)  "−"

The \B-\B magic is so that this does not apply in text, i.e. within strings or comments, because I need it still displayed as a dash there.

Unfortunately, this cause a lot of false negatives.

Is there a way to automatically display one character as another outside strings and comments?

  • 1
    Yes, there are ways to perform a replacement such as you describe. But the question is not clear (to me), because you do not attempt any replacement; you are just changing the display/appearance (using font lock), not the text. Just what are you really trying to do? Do you want to replace a character or just display it differently?
    – Drew
    Nov 26 '16 at 17:09
  • I only want to replace it. Font/colour/etc are not important. I do it in my snippet with font-lock because this is want I found on the Internet a couple of years ago for this problem. Nov 26 '16 at 17:10
  • FWIW, maybe it is not clear with the browser font you use but: The character between \\B-\\B and the one later on in "−" is different. Nov 26 '16 at 17:43
  • 1
    I'm not sure you understood @Drew 's comment. It seems to me you want to display some characters differently, but not change them in the buffer/file. Or do you?
    – JeanPierre
    Nov 26 '16 at 17:48
  • Yes, it is only about appearance. I clarified the question accordingly. Nov 26 '16 at 18:38

Testing whether some position is inside a comment or a string is hidden behind the obscurely named function syntax-ppss and its return value. I suppose the following will work.

(defun python-compose-dashs (limit)
  (while (search-forward "-" limit t)
    (unless (or (nth 3 (syntax-ppss))   ;string
                (nth 4 (syntax-ppss)))  ;comment
       (1- (point)) (point) "−" 'decompose-region))))

(add-hook 'python-mode-hook
          (lambda nil
            (font-lock-add-keywords nil '((python-compose-dashs)))))
  • Unfortunately in many cases, the dash is displayed as a minus in strings, immediately after having opened the file. If I edit the string, dashes are displayed as dashes. Dec 13 '16 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.