emacs python-mode: как выделить разными цветами строки str и unicode str - PullRequest
4 голосов
/ 29 декабря 2011

Мне бы хотелось, чтобы emacs помог мне визуально идентифицировать строки, которые не были заменены на строки Юникода (версии Python <3): </p>

"display this string in color red"

и

u"display this string in color orange"

с использованием emacs 23 и python-mode

Что мне нужно добавить в мой .emacs? Спасибо.

Ответы [ 3 ]

2 голосов
/ 13 января 2012

У меня есть что-то вроде следующего в .emacs:

(eval-after-load "python-mode"
  (add-hook 'python-mode-hook
    (lambda ()
      (font-lock-add-keywords nil
        '(("[^\\w]\\(r\\|u\\)[\'\"]" (1 font-lock-keyword-face)))))))

Который выделяет само 'u' (и 'r'), а не всю строку Может быть, этого достаточно, или вы можете найти способ адаптировать его.

1 голос
/ 26 октября 2013

В моей версии u не выделено, но строка. Вы должны быть более креативным, чем я, в отношении лиц. Я только что украл их у font-lock и изменил почти все на "red".

Если вы также хотите выделить u, вы можете поместить свойство text в него в py-font-lock-sytactic-face-function ниже. looking-back говорит вам точно, где находится u. Я просто слишком ленивый прямо сейчас. Уже поздно Кроме того, он немного "хакерский".

(defface font-lock-ucs-string-face
  '((((class grayscale) (background light)) :foreground "DarkGray" :slant italic)
    (((class grayscale) (background dark))  :foreground "DarkGray" :slant italic)
    (((class color) (min-colors 88) (background light)) :foreground "red")
    (((class color) (min-colors 88) (background dark))  :foreground "red")
    (((class color) (min-colors 16) (background light)) :foreground "red")
    (((class color) (min-colors 16) (background dark))  :foreground "red")
    (((class color) (min-colors 8)) :foreground "red")
    (t :slant italic))
  "Font Lock mode face used to highlight strings."
  :group 'font-lock-faces)


(defun py-font-lock-syntactic-face-function (state)
  "See variable `font-lock-syntactic-face-function'"
  (message "Running py-font-lock-syntactic-face-function at %d." (point))
  (if (nth 3 state)
      (if (looking-back "u\"")
      'font-lock-ucs-string-face
    'font-lock-string-face)
    'font-lock-comment-face))

(add-hook 'python-mode-hook (lambda ()
                   (setq font-lock-syntactic-face-function
                     'py-font-lock-syntactic-face-function)))
0 голосов
/ 26 октября 2013

Ю. Шен обсуждает в комментариях совершенно другой случай.Упомянутый синтаксис не анализируется простым синтаксическим анализатором (см., Например, syntax-ppss).Нужно определить свой собственный обработчик шрифтов (предпочтительно jit-lock).

В данной задаче есть особая проблема.Необходимо определить, когда пользователь завершил ввод символа, иначе каждая часть символа будет зарегистрирована в словаре и получит свой собственный цвет.Код ниже проверяет, находится ли точка вне символа.Если после символа ввести пробел, символ будет выделен.

Приведенный ниже код является лишь приблизительной реализацией одного из возможных решений.Существуют и другие, возможно, лучшие решения.

(defvar tag-font-lock-dict (make-hash-table :test 'equal)
  "Dictionary that assigns colors to tags.")
(make-variable-buffer-local 'tag-font-lock-dict)

(defvar tag-font-lock-re "#[[:alnum:]]+\\>"
  "Regular expression defining tags.")

(defvar tag-font-lock-colors (apply 'vector (cdddr (defined-colors)))
  "Vector of available colors. We should be more selective here.")

(defvar tag-font-lock-num-used-colors 0
  "Number of used colors.")
(make-variable-buffer-local 'tag-font-lock-num-used-colors)

(require 'cl)

(defun tag-font-lock-next-color ()
  "Get the next color for a new tag."
  (prog1
      (aref tag-font-lock-colors tag-font-lock-num-used-colors)
    (setq tag-font-lock-num-used-colors
      (mod (1+ tag-font-lock-num-used-colors)
           (length tag-font-lock-colors)))))

(defun tag-font-lock-handler (b e)
  "Colorize tags in region from b to e."
  (let (col ol sym (pt (point)))
    (save-excursion
      (remove-overlays b e 'tag-font-lock t) ;; No danger of splitted overlays. We have always full lines.
      (goto-char b)
      (while (re-search-forward tag-font-lock-re e 'noErr)
    (when (or (= pt (match-end 0)))
      (setq sym (match-string-no-properties 0)
        ol (make-overlay (match-beginning 0) (match-end 0))
        col (or (gethash sym tag-font-lock-dict)
            (puthash sym (tag-font-lock-next-color) tag-font-lock-dict)))
      (overlay-put ol 'face (list (list :foreground col)))
      (overlay-put ol 'tag-font-lock t)
      )))))

(defun tag-font-lock-clear ()
  "Remove color from tags in current buffer."
  (interactive)
  (remove-overlays 0 (buffer-size) 'tag-font-lock t)
  (clrhash tag-font-lock-dict))

(define-minor-mode tag-font-lock-mode
  "Highlight tags."
  :lighter " TH" ;; stands for tag highlight
  (if tag-font-lock-mode
      (progn
    (setq font-lock-extend-region-functions 'font-lock-extend-region-wholelines)
    (font-lock-mode 1)
    (jit-lock-register 'tag-font-lock-handler))
    (jit-lock-unregister 'tag-font-lock-handler)
    (tag-font-lock-clear)))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...