1

Is there a simple way to show in emacs within an self-made-mode which use emacs font-lock-mode a binary value like "0b10010010" in different colors like the zero in lite gray and the one in white color with dark background?

In my case the binary value are always 8bit long.

1
  • Asking for alternating colors on the 0s and 1s makes this tricky. If you just wanted one color for the entire pattern, you could do it by using highlight-regexp.
    – g-gundam
    Nov 1, 2022 at 15:06

1 Answer 1

4

I wrote the following a while ago, it provides a minor mode highlight-c-bits that highlights exactly your pattern. It only highlights the 1:s, but it should be trivial to extend to highlighting both 0:s and 1:s.

Technically, it first search for 0b then use a subsearch using an anchored rule to find and highlight 1:s.

;;;###autoload
(define-minor-mode highlight-c-bits-mode
  "Minor mode that highlights set bits in C-style 0b... binary constants."
  :group 'highlight-c-bits
  (if highlight-c-bits-mode
      (highlight-c-bits-add-keywords)
    (highlight-c-bits-remove-keywords))
  ;; As of Emacs 24.4, `font-lock-fontify-buffer' is not legal to
  ;; call, instead `font-lock-flush' should be used.
  (if (fboundp 'font-lock-flush)
      (font-lock-flush)
    (when font-lock-mode
      (with-no-warnings
        (font-lock-fontify-buffer)))))


;;;###autoload
(define-global-minor-mode highlight-c-bits-global-mode highlight-c-bits-mode
  (lambda ()
    (when (apply 'derived-mode-p highlight-c-bits-modes)
      (highlight-c-bits-mode 1)))
  :group 'highlight-c-bits)


(defvar highlight-c-bits-keywords
  '(("\\_<0b\\([01']+\\)\\_>"
     ("1"
      ;; PRE-MATCH-FORM:
      (progn
        (goto-char (match-beginning 0))
        (match-end 0))
      ;; POST-MATCH-FORM:
      (goto-char (match-end 1))
      (0 'font-lock-warning-face nil prepend)))))



(defun highlight-c-bits-add-keywords ()
  "Add font-lock keywords to highlight C-style 0b... binary constants."
  (font-lock-add-keywords
   nil
   highlight-c-bits-keywords
   'append))


(defun highlight-c-bits-remove-keywords ()
  "Remove font-lock keywords for highlighting C-style 0b... binary constants."
  (font-lock-remove-keywords nil highlight-c-bits-keywords))
2
  • Thank you very much! This is exact what I'm looking for. What I've changed is the color to something like (defface highlight-c-bits-font-lock-binary-number-face '((t (:background "gray70" :foreground "gray60" ))) "its a face")
    – Lars
    Nov 2, 2022 at 15:19
  • Great! If I ever get around to releasing it, I would probably define a new face for it which inherits from a suitable base face. (Any year now...) Nov 2, 2022 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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