-
Notifications
You must be signed in to change notification settings - Fork 1
/
cannon.el
364 lines (319 loc) · 12.4 KB
/
cannon.el
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
;;; cannon.el --- Simple dynamic command launcher -*- lexical-binding: t -*-
;;
;; Author: lambdart <lambdart@protonmail.com>
;; Maintainer: lambdart
;; Version: 0.0.4 Alpha
;; Homepage: https://github.com/lambdart/cannon
;; Keywords: app, launch, unix, dmenu
;;
;; This file is NOT part of GNU Emacs.
;;
;;; MIT License
;;
;; Copyright (c) 2020 lambdart
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;
;;; Commentary:
;;
;; Simulate Dmenu application launcher program
;; to dynamic/interactive launch applications/commands
;; regarding $PATH environment variable using Emacs vanilla builtin
;; facilities (minibuffer/completions).
;;
;; If you use =Exwm=, i.e, =Emacs= also as your =X Window Manager=
;; this package will be a good choice to launch =X11= applications,
;; like: =mpv=, =mupdf=, lxrandr, etc, empowering even more the
;; user experience.
;;
;; In more details, a simple lightweight application launcher that
;; has no outside dependencies (we rely on the =completing-read=
;; built-in =C= function), but if you use some narrowing/selecting
;; framework, like - =helm=, =ivy=, etc - it's easy to use =cannon= as
;; a source for candidates, just call/invoke the function
;; =cannon-get-cmd-candidates= at some point inside you =Elisp=
;; interface code to get the executable candidates.
;;
;; The name is a joke about launching =Chrome= web browser inside
;; =Emacs/Exwm=, a heavily metal ball which causes nightmares.
;;
;; PS: Works pretty well with Icomplete! (rules)!
;;
;;; Code:
(require 'seq)
(require 'cl-lib)
(require 'comint)
(require 'easy-mmode)
(defgroup cannon nil
"Very simple (exec-path) command launcher."
:group 'extensions
:group 'convenience)
(defcustom cannon-minor-mode-string (purecopy " Cannon")
"String to be display on mode-line."
:type '(choice string (const :tag "None" nil))
:group 'cannon)
(defcustom cannon-prompt "Run: "
"String to display in the initial `minibuffer' prompt."
:type 'string
:group 'cannon
:safe t)
(defcustom cannon-args-prompt "Args: "
"String to display in the arguments prompt."
:type 'string
:group 'cannon
:safe t)
(defcustom cannon-history-size 16
"A number to determinate how many recently commands should be recorded."
:type 'integer
:group 'cannon
:safe t)
(defcustom cannon-switch-to-buffer-flag t
"Non-nil means switch to the created process buffer."
:type 'bool
:group 'cannon
:safe t)
(defcustom cannon-kill-buffer-flag t
"Non-nil means automatically kill buffer when process exits."
:type 'bool
:group 'cannon
:safe t)
(defcustom cannon-debug-message-flag t
"Non-nil means show debug messages."
:type 'bool
:group 'cannon
:safe t)
(defcustom cannon-mode-hook nil
"Hooks to un after the mode was turned on."
:group 'cannon
:type 'hook)
(defcustom cannon-history-file
(expand-file-name "cache/cannon-history" user-emacs-directory)
"Cache history command file, were the command history will be saved."
:type 'string
:group 'cannon
:safe t)
(defcustom cannon-cache-file
(expand-file-name "cache/cannon-cache" user-emacs-directory)
"Cache command file, were the generated command list will be saved."
:type 'string
:group 'cannon
:safe t)
(defcustom cannon-message-prefix "[Cannon]: "
"Cannon debug message prefix."
:type 'string
:group 'cannon
:safe t)
(defvar cannon-cmd-history-list nil
"Commands history list.")
(defvar cannon-cmd-list nil
"Commands list.")
(defvar cannon-internal-vars
'(cannon-cmd-list
cannon-cmd-history-list)
"List of internal variables.")
(defvar cannon-mode nil
"Just indicates if `cannon' minor mode was initialized.
Setting this variable has no effect, use \\[cannon-mode] command instead.")
(defmacro cannon--debug-message (fmt &rest args)
"Display a internal message at the bottom of the screen.
See `message' for more information about FMT and ARGS arguments."
`(when cannon-debug-message-flag
(message (concat cannon-message-prefix ,fmt) ,@args)))
(defun cannon--clean-internal-vars ()
"Clean `cannon-internal-vars'."
(mapc (lambda (v) (set v nil)) cannon-internal-vars))
(defun cannon--default-directory ()
"Return a proper `default-directory'.
If default directory is an remote one the command will
be executed with TRAMP, this behavior isn't desired."
(if (or (null default-directory)
(file-remote-p default-directory))
temporary-file-directory
default-directory))
(defun cannon--process-sentinel (process _event)
"Cannon default PROCESS handler sentinel function."
;; handle exit process status
(and (eq 'exit (process-status process))
cannon-kill-buffer-flag
(kill-buffer (process-buffer process))))
(defun cannon--set-process-sentinel (buffer)
"Set process sentinel related to BUFFER.
Correctly handle process exit status, etc.."
(set-process-sentinel (get-buffer-process buffer)
'cannon--process-sentinel))
(defun cannon--make-comint-process (cmd cmd-line &optional args)
"Start the process defined by CMD, using `apply' and `make-comint-in-buffer'.
It's possible to use the CMD-LINE (command plus arguments).
Optional command list of ARGS (switches)."
;; parse command list from command line
(let* ((cmd-list (split-string-and-unquote cmd-line))
(program (car cmd-list)) ; parse program name
(buffer (generate-new-buffer-name (concat "*" cmd "*")))
(switches (append (cdr cmd-list) args)) ; set program switches
;; check default-directory to avoid remote execution
(default-directory (cannon--default-directory)))
;; execute command: (create a comint in buffer)
(apply #'make-comint-in-buffer cmd buffer program nil switches)))
(defun cannon--adjust-history-size ()
"Adjust command history list size."
(when (length> cannon-cmd-history-list
cannon-history-size)
(setcdr (nthcdr (- cannon-history-size 1)
cannon-cmd-history-list)
nil)))
(defun cannon--write-cache-file (file entries)
"Write ENTRIES in the target cache FILE."
(with-temp-file (expand-file-name file)
(prin1 entries (current-buffer))))
(defun cannon--read-cached-entries (file)
"Read cache FILE entries."
(let ((cache-file (expand-file-name file)))
(and (file-readable-p cache-file)
(ignore-errors
(read (with-temp-buffer
(insert-file-contents cache-file)
(buffer-substring-no-properties (point-min)
(point-max))))))))
(defun cannon--parse-cmd-entries ()
"Parse command entries defined in $PATH environment variable."
(delete-dups
(sort
(mapcar #'file-name-nondirectory
(cl-remove-if-not #'file-executable-p
(cl-mapcan
(lambda (dir)
(directory-files dir t "^[^.]"))
(cl-remove-if-not #'file-exists-p
exec-path))))
#'string<)))
(defun cannon-cmd-list ()
"Set command list from `cannon-cache-file' or create it."
(or cannon-cmd-list
(setq cannon-cmd-list
(or (cannon--read-cached-entries cannon-cache-file)
(cannon--write-cache-file cannon-cache-file
(cannon--parse-cmd-entries))))))
(defun cannon-cmd-history-list ()
"Set command list from `cannon-history-file'."
(or cannon-cmd-history-list
(setq cannon-cmd-history-list
(cannon--read-cached-entries cannon-history-file))))
(defun cannon-cmd-completions ()
"Return command completions entries merged."
(cl-union (cannon-cmd-history-list)
(cannon-cmd-list)))
(defun cannon-add-cmd-line-to-history (cmd-line)
"Add CMD-LINE to `cannon-cmd-history-list'."
(unless (member cmd-line cannon-cmd-history-list)
(push cmd-line cannon-cmd-history-list)
(cannon--adjust-history-size)))
(defun cannon-save-history ()
"Save history to `cannon-history-file'."
(cannon--write-cache-file cannon-history-file
cannon-cmd-history-list))
(defun cannon-completions-read ()
"Read string from the completions list."
(completing-read cannon-prompt
(cannon-cmd-completions)
nil
'confirm
nil))
(defun cannon-minibuffer-read (&optional arg)
"Read 'cmd-line' and its arguments if ARG is non-nil."
`(,(cannon-completions-read)
,(and arg (read-string cannon-args-prompt))))
(defun cannon-read-command-and-file ()
"Read shell command (unix) and file arguments."
`(,(cannon-completions-read)
,(read-file-name "file: " default-directory nil t)))
(defun cannon-launch (cmd-line &optional args)
"Launch a system application defined by CMD-LINE.
If ARGS is non-nil, asks for the application
arguments in a secondary prompt.
The candidates (executable names) will be parsed from
$PATH environment variable, i.e, \\[exec-path]."
;; maps command argument using the minibuffer facility
(interactive (cannon-minibuffer-read current-prefix-arg))
;; function body:
(let* ((cmd (car (split-string cmd-line)))
(args (and args (split-string-and-unquote args)))
(default-directory (cannon--default-directory)))
;; verify if command from command line was found
(if (or (not cmd) (not (executable-find cmd)))
(cannon--debug-message "Error, executable not found")
;; execute command (side effect: process buffer created)
(let ((buffer (cannon--make-comint-process cmd cmd-line args)))
(cond
;; verify if buffer was created
(buffer
;; save command line to history list
(cannon-add-cmd-line-to-history cmd-line)
;; set process sentinel
(cannon--set-process-sentinel buffer)
;; switch to buffer if flag is non-nil
(and cannon-switch-to-buffer-flag
(switch-to-buffer buffer)))
;; default: debug message
(t (cannon--debug-message "Error, fail to create *%s* buffer"
cmd)))))))
;;;###autoload
(defun cannon-command-on-file (command filename)
"Execute shell COMMAND using the chosen FILENAME as argument."
(interactive (cannon-read-command-and-file))
(async-shell-command
(format "%s %S" command (expand-file-name filename))))
;;;###autoload
(defun cannon-show-mode-state ()
"Show cannon minor mode state: on|off."
(interactive)
(message "[Cannon]: status: %s" (if cannon-mode "on" "off")))
;;;###autoload
(define-minor-mode cannon-mode
"Define a new minor mode `cannon-mode'.
This defines the toggle command `cannon-mode' and (by default)
a control variable `cannon-mode'.
Interactively with no prefix argument, it toggles the mode.
A prefix argument enables the mode if the argument is positive,
and disables it otherwise."
:group 'cannon
:global t
:lighter cannon-minor-mode-string
;; clean up
(remove-hook 'kill-emacs-hook 'cannon-save-history)
(cannon-save-history)
(cannon--clean-internal-vars)
(when cannon-mode
(add-hook 'kill-emacs-hook 'cannon-save-history)))
;;;###autoload
(defun turn-on-cannon-mode ()
"Activate the minor mode."
(interactive)
;; turn on if wasn't already initialized
(cannon-mode 1)
;; show cannon mode state
(cannon-show-mode-state))
(defun turn-off-cannon-mode ()
"Deactivate the minor mode."
(interactive)
;; turn off if necessary
(cannon-mode 0)
;; show cannon mode state
(cannon-show-mode-state))
(provide 'cannon)
;;; cannon.el ends here