unofficial mirror of bug-gnu-emacs@gnu.org 
 help / color / mirror / code / Atom feed
blob 85d182f9a098f904384bf395a10f657861a77f6e 17380 bytes (raw)
name: lisp/erc/erc-nicks.el 	 # note: path name is non-authoritative(*)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
 
;;; erc-nicks.el -- Nick colors for ERC  -*- lexical-binding: t; -*-

;; Copyright (C) 2023 Free Software Foundation, Inc.

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation, either version 3 of the License,
;; or (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; This module is heavily influenced by the lovely and more featureful
;;
;;   `erc-hl-nicks' by David Leatherman
;;    <http://www.github.com/leathekd/erc-nicks>
;;
;; which itself is based on
;;
;;   `erc-highlight-nicknames' by André Riemann, Andy Stewart, and
;;    others <https://www.emacswiki.org/emacs/ErcHighlightNicknames>
;;

;;; Code:

(require 'erc-button)
(require 'color)

(defgroup erc-nicks nil
  "Colorize nicknames in ERC buffers."
  :package-version '(ERC . "5.6") ; FIXME sync on release
  :group 'erc)

(defcustom erc-nicks-ignore-chars-regexp
  (cons (rx bot (+ (any ",`'_-"))) (rx (+ (any ",`'_-")) eot))
  "Characters surrounding a nick to ignore while highlighting.
Regexps should be suitable for `string-trim'."
  :type '(choice (cons regexp regexp) (const nil)))

(defcustom erc-nicks-skip-nicks nil
  "Nicks to not highlight."
  :type '(repeat string))

(defcustom erc-nicks-skip-faces '(erc-notice-face
                                  erc-current-nick-face erc-my-nick-face
                                  erc-pal-face erc-fool-face)
  "Faces to avoid highlighting atop."
  :type  '(repeat symbol))

(defcustom erc-nicks-nickname-face erc-button-nickname-face
  "Face to mix with generated one for emphasizing non-speakers."
  :type '(choice face (const nil)))

(defcustom erc-nicks-bg-color
  (frame-parameter (selected-frame) 'background-color)
  "Background color for calculating contrast.
Set this explicitly when the background color isn't discoverable,
which may be the case in terminal Emacs."
  :type 'string)

(defcustom erc-nicks-color-contrast-strategy
  '(erc-nicks-add-contrast erc-nicks-cap-contrast)
  "Treatments applied to colors for increasing visibility.
A value of `erc-nicks-invert' inverts a nick when it's too close
to the background.  A value of `erc-nicks-add-contrast'
attempts to find a decent contrast ratio by brightening or
darkening.  This option can also be a list, in which case,
members will be applied in the order they appear.  For example,

  \\='(erc-nicks-invert erc-nicks-add-contrast)

will invert as needed and likewise adjust the contrast.  Note
that anything specified by this option will still be applied when
`erc-nicks-colors' is a user-defined list of colors."
  :type '(choice (function-item :tag "Invert" erc-nicks-invert)
                 (function-item :tag "Add contrast" erc-nicks-add-contrast)
                 (function-item :tag "Cap contrast" erc-nicks-cap-contrast)
                 (repeat function)
                 (const nil)
                 function))

(defcustom erc-nicks-contrast-ratio '(3.5 . 12.5)
  "Desired range of contrast as a cons of (MIN . MAX).
For this to matter, `erc-nicks-color-contrast-strategy' must be
set to `erc-nicks-add-contrast' or `erc-nicks-cap-contrast' or
contain at least one if that option is a list.  If adding
contrast, MIN specifies the minimum amount allowed between a
buffer's background color and the foreground colors specified by
`erc-nicks-colors'.  The closer the number to the possible
maximum of 21(:1), the greater the contrast.  Depending on the
background, nicks are either tinted in pastel or muted with dark
gray.  MAX works similarly for reducing contrast."
  :type '(cons float float))

(defcustom erc-nicks-colors 'all
  "Pool of colors.
This can be a list of hexes or color names, such as those
provided by `defined-colors', which can itself be used when the
value is the symbol `defined'.  With `all', use any 24-bit color."
  :type '(choice (const all) (const defined) (list string)))

(defvar-local erc-nicks--face-table nil
  "Hash table containing unique nick faces.")

;; https://stackoverflow.com/questions/596216#answer-56678483
(defun erc-nicks--get-luminance (color)
  "Return relative luminance of COLOR.
COLOR can be a list of normalized values or a name."
  (let ((out 0)
        (coefficients '(0.2126 0.7152 0.0722))
        (chnls (if (stringp color) (color-name-to-rgb color) color)))
    (dolist (ch chnls out)
      (cl-incf out (* (pop coefficients)
                      (if (<= ch 0.04045)
                          (/ ch 12.92)
                        (expt (/ (+ ch 0.055) 1.055) 2.4)))))))

(defvar-local erc-nicks--bg-mode-value nil)

(defmacro erc-nicks--bg-mode ()
  `(or erc-nicks--bg-mode-value
       (setq erc-nicks--bg-mode-value
             ,(cond ((fboundp 'frame--current-background-mode)
                     '(frame--current-background-mode (selected-frame)))
                    ((fboundp 'frame--current-backround-mode)
                     '(frame--current-backround-mode (selected-frame)))
                    (t
                     '(frame-parameter (selected-frame) 'background-mode))))))

(defvar erc-nicks--grad-steps 9)
(defvar-local erc-nicks--bg-luminance nil)

;; https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html
;;
;; We could cache results, which may help when `erc-nicks-colors' is
;; set to `defined'.

(defun erc-nicks--adjust-contrast (color target &optional decrease)
  (let* ((lum-bg (or erc-nicks--bg-luminance
                     (setq erc-nicks--bg-luminance
                           (erc-nicks--get-luminance erc-nicks-bg-color))))
         (stop (if (eq (if decrease 'light 'dark) (erc-nicks--bg-mode))
                   '(1.0 1.0 1.0)
                 '(0.0 0.0 0.0)))
         (start (color-name-to-rgb color))
         ;; From `color-gradient' in color.el
         (r (nth 0 start))
         (g (nth 1 start))
         (b (nth 2 start))
         (interval (float (1+ (expt 2 erc-nicks--grad-steps))))
         (r-step (/ (- (nth 0 stop) r) interval))
         (g-step (/ (- (nth 1 stop) g) interval))
         (b-step (/ (- (nth 2 stop) b) interval))
         (maxtries erc-nicks--grad-steps)
         started)
    (while (let* ((lum-fg (erc-nicks--get-luminance (list r g b)))
                  (darker (if (< lum-bg lum-fg) lum-bg lum-fg))
                  (lighter (if (= darker lum-bg) lum-fg lum-bg))
                  (cur (/ (+ 0.05 lighter) (+ 0.05 darker)))
                  (scale (expt 2 maxtries)))
             (cond ((if decrease (> cur target) (< cur target))
                    (setq r (+ r (* r-step scale))
                          g (+ g (* g-step scale))
                          b (+ b (* b-step scale))))
                   (started
                    (setq r (- r (* r-step scale))
                          g (- g (* g-step scale))
                          b (- b (* b-step scale))))
                   (t (setq maxtries 1)))
             (unless started
               (setq started t))
             (setq r (min 1.0 (max 0 r))
                   g (min 1.0 (max 0 g))
                   b (min 1.0 (max 0 b)))
             (not (zerop (cl-decf maxtries)))))
    (color-rgb-to-hex r g b)))

(defun erc-nicks-add-contrast (color)
  "Increase COLOR's contrast by blending it with white or black.
Unless sufficient contrast exists between COLOR and the
background, raise it to somewhere around the lower bound of
`erc-nicks-contrast-ratio'."
  (erc-nicks--adjust-contrast color (car erc-nicks-contrast-ratio)))

(defun erc-nicks-cap-contrast (color)
  "Reduce COLOR's contrast by blending it with white or black.
If excessive contrast exists between COLOR and the background,
lower it to the upper bound of `erc-nicks-contrast-ratio'."
  (erc-nicks--adjust-contrast color (cdr erc-nicks-contrast-ratio) 'remove))

;; Inversion thresholds for dark and light, respectively.
(defvar erc-nicks--min-lum (/ 1 3.0))
(defvar erc-nicks--max-lum (/ 2 3.0))

(defun erc-nicks-invert (color)
  "Invert COLOR based on luminance and background."
  (if (pcase (erc-nicks--bg-mode)
        ('dark (< (erc-nicks--get-luminance color) erc-nicks--min-lum))
        ('light (> (erc-nicks--get-luminance color) erc-nicks--max-lum)))
      (pcase-let ((`(,r ,g ,b) (color-values color)))
        (format "#%04x%04x%04x" (- 65535 r) (- 65535 g) (- 65535 b)))
    color))

;; http://www.cse.yorku.ca/~oz/hash.html
;; See also gui_nick_hash_djb2_64 in weechat/src/gui/gui-nick.c,
;; which is originally from https://savannah.nongnu.org/patch/?8062.
;;
;; Short strings of the same length and those differing only in their
;; low order bits tend to land in neighboring buckets, which are often
;; similar in color.  Padding on the right with at least nine added
;; chars seems to scramble things sufficiently enough for our needs.

(defun erc-nicks--hash (s &optional nchoices)
  (let ((h 5381) ; seed and multiplier (33) hardcoded for now
        (p (or nchoices 281474976710656)) ; 48-bits (expt 2 48)
        (i 0)
        (n (length s)))
    (while (< (setq h (% (+ (* h 33) (aref s i)) p)
                    i (1+ i))
              n))
    h))

(defvar-local erc-nicks--colors-len nil)
(defvar-local erc-nicks--custom-keywords '(:group erc-nicks :group erc-faces))

(defun erc-nicks--revive (new-face old-face nick net)
  (put new-face 'erc-nicks--custom-nick (cons nick net))
  (apply #'custom-declare-face new-face (face-user-default-spec old-face)
         (format "Persistent `erc-nicks' color for %s on %s." nick net)
         erc-nicks--custom-keywords))

(defun erc-nicks--create-defface-template (face)
  (pop-to-buffer (get-buffer-create (format "*New face %s*" face)))
  (erase-buffer)
  (lisp-interaction-mode)
  (insert ";; If you *don't* use Customize, put something like this in your\n"
          (substitute-command-keys
           ";; init.el and use \\[eval-last-sexp] to apply any edits.\n\n")
          (format "(defface %s\n  '%S\n  %S"
                  face (face-user-default-spec face) (face-documentation face))
          (cl-loop for (k v) on erc-nicks--custom-keywords by #'cddr
                   concat (format "\n  %s %S" k (list 'quote v)))
          ")\n\n;; Or, if you use use-package\n(use-package erc-nicks\n"
          "  :custom-face\n"
          (format "  (%s %S)" face (face-user-default-spec face))
          ")\n"))

(defun erc-nicks--redirect-face-widget-link (args)
  (pcase args
    (`(,widget face-link . ,plist)
     (when-let* ((face (widget-value widget))
                 ((get face 'erc-nicks--custom-nick)))
       (unless (symbol-file face)
         (setf (plist-get plist :action)
               (lambda (&rest _) (erc-nicks--create-defface-template face))))
       (setf (plist-get plist :help-echo) "Create or edit `defface'."
             (cddr args) plist))))
  args)

(defun erc-nicks--get-face (nick key)
  "Retrieve or create a face for NICK, stored locally under KEY.
But favor a custom erc-nicks-NICK@NETWORK-face, when defined."
  (setq nick (erc-downcase nick))
  (let ((table (buffer-local-value 'erc-nicks--face-table
                                   (erc-server-buffer))))
    (or (gethash nick table)
        (and-let* ((face (intern-soft (concat "erc-nicks-" nick "@"
                                              (erc-network-name) "-face")))
                   ((or (and (facep face) face)
                        (erc-nicks--revive face face nick (erc-network))))))
        (let ((color (seq-reduce
                      (lambda (color strategy) (funcall strategy color))
                      (erc-list erc-nicks-color-contrast-strategy)
                      (pcase erc-nicks-colors
                        ('all (format "#%012x" (erc-nicks--hash key)))
                        ((or 'defined v)
                         (unless v (setq v (defined-colors (selected-frame))))
                         (unless erc-nicks--colors-len
                           (setq erc-nicks--colors-len (length v)))
                         (nth (erc-nicks--hash key erc-nicks--colors-len)
                              v)))))
              (new-face (make-symbol (concat "erc-nicks-" nick "-face"))))
          (face-spec-set new-face `((t :foreground ,color)) 'face-defface-spec)
          (set-face-documentation
           new-face (format "Internal face for %s on %s." nick (erc-network)))
          (puthash nick new-face table)))))

(defvar erc-nicks--phony-face nil
  "Face to pretend is propertizing the nick at point.
Modules needing to colorize nicks outside of a buttonizing
context can use this instead of setting fictitious bounds on the
`erc-button--nick' object passed to `erc-nicks--highlight'.")

(defun erc-nicks--highlight (nick-object)
  "Possibly highlight a single nick."
  (when-let*
      ((nick-object)
       (server-user (erc-button--nick-user nick-object))
       (trimmed (if erc-nicks-ignore-chars-regexp
                    (string-trim (erc-server-user-nickname server-user)
                                 (car erc-nicks-ignore-chars-regexp)
                                 (cdr erc-nicks-ignore-chars-regexp))
                  (erc-server-user-nickname server-user)))
       ((not (member trimmed erc-nicks-skip-nicks)))
       (face (or erc-nicks--phony-face
                 (get-text-property (car (erc-button--nick-bounds nick-object))
                                    'font-lock-face)))
       ((not (seq-some (lambda (f) (memq f erc-nicks-skip-faces))
                       (erc-list face)))) ; cl-notany
       ;; Ensure nicks are colored uniquely (per network) by padding
       ;; from the right, as mentioned above in `erc-nicks--hash'.
       (key (concat (erc-button--nick-downcased nick-object)
                    (and-let* ((net (erc-network))) (format "%9s" net))))
       (out (erc-nicks--get-face trimmed key)))
    ;; `font-lock-prepend-text-property' could also work if preserving
    ;; history isn't needed (in which case this var should be nil).
    (setf (erc-button--nick-erc-button-nickname-face nick-object)
          (if (or (not erc-nicks-nickname-face)
                  (eq face erc-nicks-nickname-face))
              out
            (cons out (erc-list erc-nicks-nickname-face)))))
  nick-object)

(define-erc-module nicks nil
  "Uniquely colorize nicknames in target buffers."
  ((if erc--target
       (progn
         (add-function :filter-return (local 'erc-button--modify-nick-function)
                       #'erc-nicks--highlight '((depth . 80)))
         (erc-button--phantom-users-mode +1))
     (unless erc-button-mode
       (unless (memq 'button erc-modules)
         (erc--warn-once-before-connect 'erc-nicks-mode
           "Enabling default global module `button' needed by local"
           " module `nicks'. This will impact \C-]all\C-] ERC"
           " sessions. Add `nicks' to `erc-modules' to avoid this"
           " warning. See Info:\"(erc) Modules\" for more."))
       (erc-button-mode +1))
     (when (equal erc-nicks-bg-color "unspecified-bg")
       (let ((temp (if (eq (erc-nicks--bg-mode) 'light) "white" "black")))
         (erc-button--display-error-notice-with-keys
          "Module `nicks' unable to determine background color.  Setting to \""
          temp "\" globally.  Please see `erc-nicks-bg-color'.")
         (custom-set-variables (list 'erc-nicks-bg-color temp))))
     (setq erc-nicks--face-table (make-hash-table :test #'equal)))
   (setf (alist-get "Edit face" erc--nick-popup-alist nil nil #'equal)
         #'erc-nicks-customize-face)
   (advice-add 'widget-create-child-and-convert :filter-args
               #'erc-nicks--redirect-face-widget-link))
  ((kill-local-variable 'erc-nicks--face-table)
   (kill-local-variable 'erc-nicks--bg-mode-value)
   (kill-local-variable 'erc-nicks--bg-luminance)
   (kill-local-variable 'erc-nicks--colors-len)
   (when (fboundp 'erc-button--phantom-users-mode)
     (erc-button--phantom-users-mode -1))
   (remove-function (local 'erc-button--modify-nick-function)
                    #'erc-nicks--highlight)
   (setf (alist-get "Edit face" erc--nick-popup-alist nil 'remove #'equal)
         nil))
  'local)

(defun erc-nicks-customize-face (nick)
  "Customize or create persistent face for NICK."
  (interactive (list (or (car (get-text-property (point) 'erc-data))
                         (completing-read "nick: " (or erc-channel-users
                                                       erc-server-users)))))
  (setq nick (erc-downcase (substring-no-properties nick)))
  (let* ((net (erc-network))
         (key (concat nick (and net (format "%9s" net))))
         (old-face (erc-nicks--get-face nick key))
         (new-face (intern (format "erc-nicks-%s@%s-face" nick net))))
    (unless (eq new-face old-face)
      (erc-nicks--revive new-face old-face nick net)
      (set-face-attribute old-face nil :foreground 'unspecified)
      (set-face-attribute old-face nil :inherit new-face))
    (customize-face new-face)))

(provide 'erc-nicks)

;;; erc-nicks.el ends here

debug log:

solving 85d182f9a09 ...
found 85d182f9a09 in https://yhetil.org/emacs-bugs/87v8gjrwwo.fsf__25148.7589253642$1684849113$gmane$org@neverwas.me/
found 53d1e0cc592 in https://yhetil.org/emacs-bugs/87ilcp1za1.fsf__10272.1162418433$1684420707$gmane$org@neverwas.me/

applying [1/2] https://yhetil.org/emacs-bugs/87ilcp1za1.fsf__10272.1162418433$1684420707$gmane$org@neverwas.me/
diff --git a/lisp/erc/erc-nicks.el b/lisp/erc/erc-nicks.el
new file mode 100644
index 00000000000..53d1e0cc592


applying [2/2] https://yhetil.org/emacs-bugs/87v8gjrwwo.fsf__25148.7589253642$1684849113$gmane$org@neverwas.me/
diff --git a/lisp/erc/erc-nicks.el b/lisp/erc/erc-nicks.el
index 53d1e0cc592..85d182f9a09 100644

Checking patch lisp/erc/erc-nicks.el...
Applied patch lisp/erc/erc-nicks.el cleanly.
Checking patch lisp/erc/erc-nicks.el...
Applied patch lisp/erc/erc-nicks.el cleanly.

skipping https://yhetil.org/emacs-bugs/87v8gjrwwo.fsf__25148.7589253642$1684849113$gmane$org@neverwas.me/ for 85d182f9a09
index at:
100644 85d182f9a098f904384bf395a10f657861a77f6e	lisp/erc/erc-nicks.el

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).