# selecting-read.el -rw-r--r-- 13.2 KiB View raw
                                                                                
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
;;; selecting-read.el --- Utility function for selection  -*- lexical-binding: t; -*-

;; Copyright (C) 2021  Philip Kaludercic

;; Author: Philip Kaludercic <philipk@posteo.net>
;; Keywords: lisp

;; This program 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.

;; This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; Selecting Framework for Emacs.

;;; Code:

(eval-when-compile (require 'subr-x))
(require 'cl-lib)
(require 'cl-generic)

(defgroup selecting-read nil
  "Utility function for selection."
  :group 'convenience)

(defcustom selecting-read-indent 1
  "Number of columns to indent subtrees by."
  :type 'number)

(defcustom selecting-read-display-action
  '(display-buffer-in-side-window
    (window-height . 0.25)
    (side . right))
  "Specification on how to display a `selecting-read' buffer."
  :type display-buffer--action-custom-type)

(defcustom selecting-read-auto-narrow nil
  "Jump directly into narrowing mode."
  :type 'boolean)

(defface selecting-read-candidate-face
  '((t :inherit highlight :extend t))
  "Face to use for selection candidate.")

(defvar selecting-read-function #'selecting-read-default
  "Function called by `selecting-read'.
This function must accept two variables LIST and OPTIONS.
LIST may be a list or an alist.
OPTIONS may consist of the following keys:

:multiple

  If non-nil, `selecting-read' will return multiple results in
  form of a list.")

(defvar selecting-read-buffer nil
  "Buffer used by `selecting-read'.")

;;; object framework
(cl-defgeneric selecting-read-represent (object)
  "Return a string to represent OBJECT.")

(cl-defgeneric selecting-read-properties (object)
  "Return a plist of properties for OBJECT."
  (ignore object))

(cl-defgeneric selecting-read-children (object)
  "Return a list of children for OBJECT."
  (ignore object))

(cl-defgeneric selecting-read-flags (object)
  "Return a list of symbols indicating flags for OBJECT."
  (ignore object))

;;;; simple string object
(cl-defmethod selecting-read-represent ((str string))
  "A string STR represents itself."
  str)

;;;; generic node object
(cl-defmethod selecting-read-represent ((node (head node)))
  "Return representation for NODE (node OBJECT CHILDREN).
OBJECT may be a string or a cons cell (REPRESENTATION
. PROPERTIES).  If REPRESENTATION or OBJECT is string, then this
string will be returned.  If REPRESENTATION or OBJECT is a
function, this function will be called with no arguments.  It is
expected to return a string that will be returned by this
method."
  (let ((represent (if (consp (cadr node))
		       (caadr node)
		     (cadr node))))
    (cond ((functionp represent) (funcall represent))
	  ((stringp represent) represent)
	  ((error "Invalid representation")))))

(cl-defmethod selecting-read-properties ((node (head node)))
  "Return properties for NODE (node OBJECT CHILDREN).
OBJECT may be a string or a cons cell (REPRESENTATION
. PROPERTIES)."
  (and (consp (cadr node))
       (cdadr node)))

(cl-defmethod selecting-read-children ((node (head node)))
  "Return children for NODE (node REPRESENTATION CHILDREN)."
  (cddr node))

;;; default UI
(defvar-local selecting-read-list nil)
(defvar-local selecting-read-options nil)
(defvar-local selecting-read-selection nil)
(defvar-local selecting-read-hl-overlay nil)
(defvar selecting-read-query nil)

(defun selecting-read-select ()
  "Select object at point."
  (interactive)
  (with-current-buffer selecting-read-buffer
    (when-let ((object (get-text-property (overlay-start selecting-read-hl-overlay)
					  'selecting-read-object)))
     (when (memq 'non-selectable (selecting-read-flags object))
       (user-error "This object is not selectable"))
     (unless (plist-get selecting-read-options :multiple)
       (setq selecting-read-selection object)))
   (if selecting-read-auto-narrow
       (unless selecting-read-selection
	 (message "Nothing selected")
	 (sit-for 0.5))
     (exit-recursive-edit))))

(defun selecting-read-cycle ()
  "Show or hide the children of the current object."
  (interactive)
  (if-let ((ov (get-text-property (point) 'selecting-read-sub)))
      (overlay-put ov 'invisible
		   (if (eq (overlay-get ov 'invisible) 'selecting-read)
		       nil 'selecting-read))
    (user-error "No children")))

(defun selecting-read-narrow (query)
  "Narrow listing to options that much regexp QUERY."
  (interactive (list (read-string "Narrow: " selecting-read-query)))
  (setq selecting-read-query query)
  (selecting-read-redraw))

(defun selecting-read-interactive-narrow ()
  "Narrow selection after every command and select what is left."
  (interactive)
  (minibuffer-with-setup-hook
      (lambda ()
	(let ((last-query ""))
	  (add-hook 'post-command-hook
		    (lambda ()
		      (let ((query (minibuffer-contents)))
			(unless (string-equal last-query query)
			  (selecting-read-narrow query))
			(setq last-query query)))
		    nil t))
	(add-hook 'post-command-hook #'selecting-read-hl-current nil t)
	(local-set-key [remap previous-line] #'selecting-read-previous)
	(local-set-key [remap next-line] #'selecting-read-next))
    (if (plist-get selecting-read-options :must-select)
	(while (not selecting-read-selection)
	  (read-string "Narrow: " selecting-read-query)
	  (selecting-read-select))
      (read-string "Narrow: " selecting-read-query)
      (selecting-read-select))))

(defun selecting-read-mark ()
  "Add object at point to selection."
  (interactive)
  (unless (plist-get selecting-read-options :multiple)
    (user-error "Cannot mark multiple elements"))
  (push (get-text-property (point) 'selecting-read-object)
	selecting-read-selection))

(defun selecting-read-next ()
  "Move to next object."
  (interactive)
  (with-selected-window (get-buffer-window selecting-read-buffer)
    (goto-char (or (next-single-property-change (point) 'selecting-read-object)
		   (point)))))

(defun selecting-read-previous ()
  "Move to previous object."
  (interactive)
  (with-selected-window (get-buffer-window selecting-read-buffer)
    (goto-char (or (previous-single-property-change (point) 'selecting-read-object)
		   (point-min)))))

(defun selecting-read-hl-current ()
  "Highlight current object at point."
  (with-current-buffer selecting-read-buffer
    (move-overlay selecting-read-hl-overlay
		  (or (previous-single-property-change
		       (min (1+ (point)) (point-max))
		       'selecting-read-object)
		      (point-min))
		  (or (next-single-property-change
		       (point)
		       'selecting-read-object)
		      (point-max)))))

(defun selecting-read-quit (force)
  "Attempt to quit selection.
With a prefix argument or non-nil value for FORCE, force quitting
even if an argument is requested."
  (interactive (list (or (eq last-command #'selecting-read-quit)
			 (eq this-command #'keyboard-quit)
			 current-prefix-arg)))
  (if (and (not force) (plist-get selecting-read-options :must-select))
      (message (substitute-command-keys "Must select an object.  \
Press \\[selecting-read-quit] again to force-quit."))
    (abort-recursive-edit)))

(defvar selecting-read-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map (kbd "q")			#'selecting-read-quit)
    (define-key map [remap keyboard-quit]	#'selecting-read-quit)
    (define-key map (kbd "<return>")		#'selecting-read-select)
    (define-key map (kbd "<tab>")		#'selecting-read-cycle)
    (define-key map (kbd "/")			#'selecting-read-narrow)
    (define-key map (kbd "m")			#'selecting-read-mark)
    (define-key map (kbd "n")			#'selecting-read-next)
    (define-key map (kbd "p")			#'selecting-read-previous)
    map))

(define-derived-mode selecting-read-mode special-mode "Selecting Read"
  "Major mode for Selecting Read buffers."
  (setq-local selecting-read-hl-overlay (make-overlay 0 0))
  (overlay-put selecting-read-hl-overlay 'face 'selecting-read-candidate-face)
  (add-hook 'post-command-hook #'selecting-read-hl-current nil t)
  (add-to-invisibility-spec 'selecting-read)
  (setq-local mode-line-format " Select using RET")
  (setq-local cursor-type nil))

(defun selecting-read-draw (list depth)
  "Insert LIST indented by DEPTH."
  (dolist (object list)
    (let ((string (selecting-read-represent object))
	  (properties (selecting-read-properties object))
	  (children (selecting-read-children object))
	  (start (point)))
      (when (or (not selecting-read-query)
		(string-match-p selecting-read-query string))
	(insert string)
	(unless (bolp) (insert ?\n)))	;ensure newline
      (let ((mid (make-marker)))
	(cl-loop for (key val) on properties by #'cddr
		 do (insert (propertize (symbol-name key) 'face 'shadow)
			    " \t"
			    (cond ((stringp val) val)
				  ((functionp val) (funcall val object))
				  ((prin1-to-string val)))
			    "\n"))
	(set-marker mid (point))
	(selecting-read-draw children (1+ depth))
	;; TODO: allow lazy subtree computation
	(when children
	  (let ((sub (make-overlay mid (point))))
	    (overlay-put sub 'priority (- depth))
	    (add-text-properties start mid (list 'selecting-read-sub sub))
	    (when (memq 'folded (selecting-read-flags object))
	      (overlay-put sub 'invisible 'selecting-read))))
	(when (> depth 0)
	  (indent-rigidly start mid (* depth selecting-read-indent)))
	(add-text-properties start mid (list 'selecting-read-object object
					     'mouse-face 'match))))))

(defun selecting-read-redraw ()
  "Redraw current buffer."
  (with-current-buffer selecting-read-buffer
    (let ((inhibit-read-only t))
      (erase-buffer)
      (selecting-read-draw selecting-read-list 0)
      (goto-char (point-min))
      (selecting-read-hl-current))))

(defun selecting-read-initialize (list options)
  "Initialize a Selecting Read buffer for LIST.
OPTIONS is a plist as specified in `selecting-read-function'."
  (selecting-read-mode)
  (setq selecting-read-options options)
  (setq selecting-read-list list)
  (setq header-line-format (plist-get selecting-read-options :prompt))
  (setq selecting-read-query (plist-get selecting-read-options :initial-query))
  (selecting-read-redraw))

(defun selecting-read-default (list options)
  "Default selection function.
LIST and OPTIONS are passed directly from `selecting-read'."
  (with-current-buffer (generate-new-buffer " *Selecting Read*")
    (setq selecting-read-buffer (current-buffer))
    (select-window (funcall (car selecting-read-display-action)
			    (current-buffer)
			    (cdr selecting-read-display-action)))
    (let (return-value)
      (unwind-protect
	  (progn
	    (selecting-read-initialize list options)
	    (if selecting-read-auto-narrow
		(selecting-read-interactive-narrow)
	      (recursive-edit)))
	(setq return-value selecting-read-selection)
	(setq selecting-read-query nil)
	(kill-buffer))
      return-value)))

(defun selecting-read-generate-gui-menu (list)
  "Generate a keymap menu for LIST."
  (let ((map (make-sparse-keymap)))
    (dolist (object list)
      (let ((string (selecting-read-represent object))
	    ;; (properties (selecting-read-properties object))
	    (children (selecting-read-children object)))
	(define-key
	  map object
	  `(menu-item ,string
		      ,(if children
			   (selecting-read-generate-gui-menu children)
			 t)))
	(when children
	  (define-key map object `(menu-item "<select>" t)))))
    map))

(defun selecting-read-gui (list _option)
  "Select an option using GUI menus.
LIST and OPTIONS are passed directly from `selecting-read'."
  (let ((selection (x-popup-menu t (selecting-read-generate-gui-menu list))))
    (if (vectorp selection)
	(aref selection (1- (length selection)))
      (error "No selection"))))

;;;###autoload
(defun selecting-read (list &rest options)
  "Ask user to select an element from LIST.
LIST and the plist OPTIONS are passed to the function
designated by `selecting-read-function'."
  (cl-assert (= (mod (length options) 2) 0)
	     nil "Incomplete property list.")
  (cl-assert (cl-loop for (key _val) on options by #'cddr
		      always (keywordp key))
	     nil "Degenerated property list.")
  (funcall selecting-read-function list options))

(defun selecting-read-<-completing-read (prompt collection &optional
					       predicate
					       require-match
					       initial-input
					       _hist
					       default
					       _inherit-input-method)
  "Translation interface for `completing-read' to `selecting-read'.
PROMPT, COLLECTION, PREDICATE, REQUIRE-MATCH, INITIAL-INPUT and
DEFAULT are all interpreted as by `completing-read'."
  (or (selecting-read (all-completions "" collection predicate)
		      :must-select (not (memq require-match
					      '(confirm-after-completion
						confirm
						nil)))
		      :initial-query initial-input
		      :prompt prompt)
      (cond ((listp default) (car default))
	    ((null default) "")
	    (default))))

(setq completing-read-function #'completing-read-default)
;; (setq completing-read-function #'selecting-read-<-completing-read)

(provide 'selecting-read)
;;; selecting-read.el ends here