3

I am trying to simplify the editing of a CSV file in Emacs. I would like to hightlight the first field of each row/line in different font foreground color. For example

KEYWORD1,description,value
KEYWORD2,description,value
KEYWORD3,description,value
KEYWORD4,description,value

I would like to highlight KEYWORD1, KEYWORD2, KEYWORD3, and KEYWORD4 in a different color. I tried to install csv-mode but it seems it does not offer this feature. I am using GNU Emacs 24.3.1 on Ubuntu 12.04.

2 Answers 2

4

Assuming csv-mode is a normal mode (I did not have it installed), this should work out of the box:

(add-hook 'csv-mode-hook
          (lambda ()
            (font-lock-add-keywords nil '(("^\\([^,]*\\)," 1 'font-lock-function-name-face)))))

Just replace font-lock-function-name-face with the face of your choice, if you don't like that particular color

1
  • Perfect! It also updates added lines immediately. Thank you very much. Jun 4, 2014 at 20:47
2

I experimented a little bit with text properties, and came up with

(defun csv-highlight-1 ()
  (interactive)
  (save-excursion 
    (beginning-of-buffer)
    (setq spos t)
    (while spos
      (setq spos (re-search-forward "^[^,]*," nil t))
      (when spos
        (let ((mod (buffer-modified-p)) (pos1 (line-beginning-position)) (pos2 (- spos 1)))
        (put-text-property pos1 pos2 'font-lock-face '(:foreground "red"))
        (put-text-property pos1 pos2 'front-sticky t)
        (set-buffer-modified-p mod))))))

It seems to work, but I have to call it manually each time I update the buffer. But maybe that is ok.

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.