-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinit.el
14890 lines (12893 loc) · 526 KB
/
init.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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; index.el --- isamert's configuration -*- lexical-binding: t; -*-
;;; Commentary:
;; isamert's configuration
;; This is my Emacs configuration. My main focus is sanity. I'm a
;; person who get frustrated pretty easily. So instead of optimizing
;; the time spent on doing things, I try to find ways of doing things
;; that does not make me frustrated. Most of the time you get speed
;; boost as a byproduct.
;;;; Emacs installation
;; I use my distributions package manager to install Emacs. However,
;; in MacOS (my work computer) I use /homebrew/ and /emacs-plus/
;; formula. Here is how you install it:
;;
;; #+begin_src sh
;; brew tap d12frosted/emacs-plus
;; brew install emacs-plus@30 \
;; --with-dragon-icon \
;; --with-dbus \
;; --with-imagemagick \
;; --with-poll \
;; --with-debug
;; #+end_src
;;
;; There are also other nice Emacs distributions, like:
;;
;; - /~https://github.com/jimeh/emacs-builds
;; - https://emacsformacosx.com/
;;
;; But I need the aforementioned switches and patches. Otherwise these
;; are very good.
;;
;; * --with-poll
;;
;; You can read about the options [[/~https://github.com/d12frosted/homebrew-emacs-plus#options][here]], but the most important one is
;; ~--with-poll~. Otherwise you'll get lot's of /no file descriptors
;; left, too many files are open/ errors, especially if you are using
;; LSP etc..
;;
;; * --with-debug
;;
;; It is nice for debugging crashes or freezes. Helps you get a better
;; output from the debugger. When Emacs freezes and ~pkill -USR2 Emacs~
;; is not helping, what you can do to debug the issue is:
;;
;; #+begin_src sh
;; $ cd ~/Library/Caches/Homebrew/emacs-plus@30--git/src
;; $ lldb --local-lldbinit /opt/homebrew/Cellar/emacs-plus@30/<VERSION>/Emacs.app
;; (lldb) r # → Do this to start emacs
;; # wait for the freeze
;; # C-c to quit the Emacs after freeze
;; (lldb) xbacktrace # or bt
;; #+end_src
;;
;; Same story with crashes. Just run Emacs through =lldb= all the time
;; and be prepared I guess...
;;;; Usage notes
;;;;; General notes and conventions
;; - This configuration is meant to be used with /emacs daemon/, so I don't really care about the startup time etc.
;; - I try to split package configurations into multiple org src blocks and unify them using ~noweb~ references under a single =use-package= directive.
;; - I try to put things in way that easily copyable from the configuration. An example would be using multiple =(setq ...)= lines instead of having one =(setq ... ...)= call and setting multiple variables in one go.
;; - I make use of =use-package= features quite minimally. See [[id:3d974e67-11fc-4f07-8cd4-ec6fd63152c4][here]] for more information that. This is generally related with the item above and future-proofing.
;; - I use =verbatim text= and ~code text~ completely randomly.
;; - I try to prefer built-in packages or packages that enhances built-in ones where possible. I'm also trying to simplify my configuration, so another goal is to reduce the package number. Although I intend to keep packages that enhances the overall experience with no special configuration (just install and forget type of packages).
;;;;; Keybinding conventions
;; - After leader
;; - =e= :: is reserved for independent programs, that is not related to editing/programming. For example, "ec" opens calendar, "ee" opens elfeed, "er..." controls the radio.
;; - =t= :: is reserved for toggling stuff. Toggle the terminal, toggle a frequently accessed buffer etc.
;; - =h= :: is reserved for any menu with fuzzy selection that does not fit anywhere else.
;; - =g= :: is for git related functionality.
;; - =p= :: is for project related functionality.
;; - =/= :: is for search/translate related functionality. (Generally external programs)
;; - =b= :: is for buffers.
;; - =w= :: is for windows. I also use =C-w= for this, which is default prefix for window-related functions in vim.
;; - =o= :: is for org-mode/outline mode.
;;;;; Updating packages
;; Just do ~M-x straight-pull-all~. I do this quite infrequently. If
;; everything is working fine as it is, I tend to not update anything.
;;; Code:
;;;; Preparation
;;;;; straight.el and use-package
;; Useful to see which packages take long time to load
;; (require 'use-package)
;; (setq use-package-compute-statistics t)
(setq use-package-enable-imenu-support t) ;; With that, IMenu will show packages section
(defvar bootstrap-version)
(defvar straight-base-dir)
(let ((bootstrap-file
(expand-file-name "straight/repos/straight.el/bootstrap.el" (or (ignore-errors straight-base-dir) user-emacs-directory)))
(bootstrap-version 5))
(unless (file-exists-p bootstrap-file)
(with-current-buffer
(url-retrieve-synchronously
"https://raw.githubusercontent.com/raxod502/straight.el/develop/install.el"
'silent 'inhibit-cookies)
(goto-char (point-max))
(eval-print-last-sexp)))
(load bootstrap-file nil 'nomessage))
(straight-use-package 'use-package)
(use-package straight
:custom (straight-use-package-by-default t))
;; I tend to not use the =use-package= goodies while configuring my
;; packages, meaning that I don't use =:hook=, =:bind= etc. as they
;; have relatively simpler alternatives in Emacs and using
;; =use-package= alternatives of these makes copy/pasting harder. Here
;; are the keywords that I use the most:
;; - =:init= :: This gets called before the package gets initialized.
;; - =:config= :: This gets called after the package is initialized.
;; - =:after= :: This makes the current definition to wait the loading of listed packages, like =:after (evil org)= makes it wait for the =evil= and =org= packages to be loaded.
;; - =:if= :: Loads the package conditionally, like =:if (eq system-type 'darwin)=.
;;;;;; Hiding mode indicators from modeline
;; ~diminish.el~ provides a way to hide mode indicators from mode
;; line. Either pass ~:diminish t~ to use-package while installing or
;; just call ~(diminish 'x-mode)~.
;; (use-package diminish)
;; Currently I use [[mini-modeline]] as my modeline and it already
;; hides minor mode indicators from the modeline. So this package is
;; not needed but better have it as I might change my modeline in the
;; future.
;;;;; Load path
(defconst im-load-path (expand-file-name "~/.emacs.d/load/")
"The path that I keep my extra stuff.
Probably stuff that not committed to git.")
(defconst im-packages-path (expand-file-name "~/.emacs.d/packages/")
"The path that I keep my experimental packages in.
These packages are not published as a separate project but lives
in my dotfiles repository.")
(add-to-list 'load-path im-load-path)
(add-to-list 'load-path im-packages-path)
;; Also load ~im-secrets~ from =load-path=. I'll be utilizing some
;; variables defined here throughout my configuration. It contains
;; some api-keys, some tokens or some passwords etc. that I don't want
;; to leak into public. Instead of doing mutations on an external
;; hidden script, I define variables in this external hidden script
;; and reference them in the configuration. This way the logic stays
;; in the public configuration file so that everyone can take a look,
;; but only the variable itself will be hidden from the public.
(require 'im-secrets)
;;;;; Essential packages
;; I use =s.el= and =dash.el= extensively. They already come as a
;; dependency with other packages but I may use them before loading
;; any package, so:
(use-package dash
:demand t
:config (require 'dash))
(use-package s
:demand t
:config (require 's))
(use-package yaml)
;; Following provides defmemoize macro. Use (memoize-restore
;; 'fn-name) to restore the original function.
(use-package memoize)
;; Web server stuff. `elnode-make-webserver' is very useful for
;; starting a webserver in given directory. Use `elnode-server-list'
;; to list active webservers.
(use-package elnode
:defer t
:custom
(elnode-error-log-to-messages nil))
;; JS-like async/await. Simply return a promise from a function with
;;
;; #+begin_src elisp
;; (promise-new
;; (lambda (resolve reject)
;; (funcall resolve arg)))
;; #+end_src
;;
;; and then
;;
;; #+begin_src elisp
;; (async-defun some-function ()
;; (message "Result is %s" (await promise-returned-function)))
;; #+end_src
;;
(use-package async-await
:autoload (async-defun))
(use-package im-async-await
:straight nil
:autoload (async-cl-defun)
:defer t)
(use-package request
:custom
(request-log-level 'warn)
(request-message-level -1))
;;;;;; emacs-async
;; To be able execute elisp asynchronously. Of course this has lot's
;; of limitations, the lambda passed to ~async-start~ will be executed
;; in a freshly started Emacs instance and it will not have the any
;; context of the currently running Emacs instance. There are ways to
;; pass variables into the context of newly created Emacs instance
;; which helps a lot.
(use-package async)
;;;;;; parse-csv
(use-package parse-csv)
(defun im-parse-csv (csv)
"Parse CSV into an elisp object.
CSV is a string that contains the csv data. The first line should be
the header line."
(let* ((parsed (parse-csv-string-rows csv ?\, ?\" "\n"))
(headers (car (-take 1 parsed)))
(data (-drop 1 parsed)))
(--map (-zip-pair headers it) data)))
(defun im-parse-csv-buffer ()
"Parse a CSV buffer into an elisp list and inspect it."
(interactive)
(im-inspect (im-parse-csv (buffer-substring-no-properties (point-min) (point-max)))))
(autoload 'parse-csv-string-rows "parse-csv")
;;;;;; midnight-mode
;; I run some functions periodically using midnight-mode. Runs once a
;; day at the specified time. Simply add your function via ~add-hook~
;; to ~midnight-hook~.
(use-package midnight
:straight (:type built-in)
:demand t
:config
;; From: https://old.reddit.com/r/emacs/comments/y4nc0e/help_needed_with_midnightmode/
;; To make it *not* work at each emacs startup, use numbers instead of "10:30am"
;;
;; Set it to 10:30am because some jobs require VPN to be open.
(midnight-delay-set 'midnight-delay (truncate (* 10.5 60 60)))
(midnight-mode +1))
;;;;; Variables and functions
;; Some basic variable and function definitions that will be used in
;; configuration.
;;;;;; General utilities
(defun im-mkdir-if-not (dir)
"Create the DIR if it does not exist return DIR."
(unless (file-exists-p dir)
(make-directory dir))
dir)
(defun im-font-exists-p (font)
"Check if FONT exists."
(x-list-fonts font))
(defun im-assoc-regexp (key list &optional fn)
"Like `assoc` but uses `string-match (car pair) KEY` for
comparison and returns all the matching pairs. FN is applied to
the keys before matching, if present."
(seq-filter
(lambda (pair)
(when (string-match-p (if fn (funcall fn (car pair)) (car pair)) key)
pair))
list))
(defun im-region-or (what &optional alternative)
"Return currently selected string or WHAT-at-point string.
WHAT can be \\='symbol \\='word or a function that returns string
etc.
If WHAT is \\='string, then when no region is found user is
prompted with `read-string'.
If WHAT is a literal string, then it's treated as an argument to
`skip-chars-forward' and `skip-chars-forward'.
If ALTERNATIVE is non-nil, then if the result of WHAT returns nil
then `im-region-or' is called with ALTERNATIVE. A useful example
would be providing \\='string as ALTERNATIVE so that if a match
not found with WHAT, then it is requested from the user."
(let ((result (cond
((use-region-p) (buffer-substring-no-properties (region-beginning) (region-end)))
((equal what 'string) (read-string "Enter value: "))
((functionp what) (funcall what))
((symbolp what) (thing-at-point what t))
((stringp what)
(save-excursion
(let* ((start (progn (skip-chars-backward "0-9") (point)))
(end (progn (skip-chars-forward "0-9") (point)))
(x (buffer-substring-no-properties start end)))
(if (s-blank? x) nil x))))
(t what))))
(if result
result
(if alternative
(im-region-or alternative)
result))))
(defun get-integer-at-cursor ()
"Get the integer at the cursor."
(save-excursion
(let ((start (progn (skip-chars-backward "0-9") (point)))
(end (progn (skip-chars-forward "0-9") (point))))
(string-to-number (buffer-substring start end)))))
(defun im-inner-back-quote-at-point ()
"Return text inside the back quotes at point."
(let ((bounds (evil-inner-back-quote)))
(buffer-substring-no-properties
(nth 0 bounds)
(nth 1 bounds))))
(defun im-shell-command-to-string (cmd)
"Like `shell-command-to-string' but only stdout is returned."
(string-trim
(with-output-to-string
(with-current-buffer standard-output
(process-file
shell-file-name nil '(t nil) nil shell-command-switch
cmd)))))
(defun im-serialize-into-file (file data)
(unless (f-exists? (f-dirname file))
(f-mkdir-full-path (f-dirname file)))
(with-temp-file (expand-file-name file)
(let ((print-length nil)
(print-level nil))
(prin1 data (current-buffer)))))
(defun im-deserialize-from-file (file)
(let ((fpath (expand-file-name file)))
(when (and (file-exists-p fpath))
(with-temp-buffer
(insert-file-contents fpath)
(goto-char (point-min))
(read (current-buffer))))))
;; TODO Add a way to invalidate the file after given date
(defmacro defmemoizefile (name arglist file &rest body)
"Like a normal memoize function but persist the memoize cache to
a file so that when Emacs is opened freshly, it'll continue using
the memoize cache."
(declare (indent 3) (doc-string 4))
(let ((origfn (intern (concat (symbol-name name) "---defmemoizefile-origfn")))
(memoizemap (intern (concat (symbol-name name) "---defmemoizefile-memoizemap"))))
`(progn
(setq ,memoizemap (make-hash-table :test 'equal))
(when (file-exists-p (expand-file-name ,file))
(setq ,memoizemap (im-deserialize-from-file ,file)))
(defun ,origfn ,arglist
,@body)
(defun ,name (&rest ___args)
(if-let ((memoizedresult (gethash ___args ,memoizemap)))
memoizedresult
(let ((___result (apply #',origfn ___args)))
(map-put! ,memoizemap ___args ___result)
(im-serialize-into-file ,file ,memoizemap)
___result))))))
(defun im-select-window-with-buffer (buffer-name)
"Select the visible window that matches given BUFFER-NAME.
If more than one buffer is matched, then let user interactively
select the right window using `aw-select'."
(declare (indent 1))
(let* ((curr (buffer-name (current-buffer)))
(windows (--filter
(-as-> (window-buffer it) buffer
(buffer-name buffer)
(and (string-match buffer-name buffer) (not (equal curr buffer))))
(window-list))))
(select-window
(if (= 1 (length windows))
(car windows)
(cl-letf (((symbol-function 'aw-window-list) (lambda () (sort `(,@windows ,(selected-window)) 'aw-window<))))
(aw-select nil))))))
(defmacro im-with-visible-buffer (buffer-name &rest body)
"Evaluate BODY within the BUFFER-NAME that is currently visible."
(declare (indent 1))
`(with-selected-window (selected-window)
(when (im-select-window-with-buffer ,buffer-name)
,@body)))
(defun im-sync-async-command-to-string (command &rest args)
"Run async command and wait until it's finished. This may seem stupid but I had to use it."
(with-temp-buffer
(let ((process (apply 'start-process `("sync-async-proc" ,(current-buffer) ,command ,@args))))
(while (process-live-p process)
(sit-for 0.1))
(buffer-string))))
(defun im-plist-to-alist (plist)
"Convert PLIST to an alist.
Taken from transient.el."
(let (alist)
(while plist
(push (cons (let* ((symbol (pop plist))
(name (symbol-name symbol)))
(if (eq (aref name 0) ?:)
(intern (substring name 1))
symbol))
(pop plist))
alist))
(nreverse alist)))
(defmacro let-plist (plist &rest form)
"Like `let-alist' but for plists."
(declare (indent 1))
`(let-alist (im-plist-to-alist ,plist)
,@form))
(defun im-mimetype (path)
"Return mimetype of given file at PATH."
(string-trim (shell-command-to-string (format "file --brief --mime-type '%s'" path))))
(defun im-to-keyword (it)
"Convert given string or symbol to a :keyword."
(thread-last
(cond
((stringp it) it)
((symbolp it) (symbol-name it))
(t (error "Trying to convert %s to symbol" it)))
(string-remove-prefix ":")
(concat ":")
(downcase)
(intern)))
(defun im-alist-to-plist (alist)
"Convert association list ALIST into the equivalent property-list form.
The plist is returned. This converts from
\((a . 1) (b . 2) (c . 3))
into
\(:a 1 :b 2 :c 3)
The original alist is not modified.
This function is taken from `mm-decode.el' and modified."
(let (plist)
(while alist
(let ((el (car alist)))
(setq plist (cons (cdr el) (cons (im-to-keyword (car el)) plist))))
(setq alist (cdr alist)))
(nreverse plist)))
(defmacro λ-interactive (&rest body)
"Useful for defining keybindings."
`(lambda () (interactive) ,@body))
(defun im-kill (x &optional replace)
(kill-new x replace)
x)
(defun im-force-focus-emacs ()
"Focus Emacs frame if not focused already."
(unless (frame-focus-state)
(im-when-on
:darwin
(shell-command-to-string
"osascript -e 'tell application \"System Events\" to click UI element \"Emacs\" of list 1 of application process \"Dock\"'")
:linux
(user-error "Implement this: im-force-focus-emacs"))))
(defun im-line-count-below-cursor ()
"Return the number of lines displayed below the cursor in the current window."
(let ((line (line-number-at-pos)))
(save-excursion
(move-to-window-line 0)
(- (window-height) (- line (line-number-at-pos))))))
;;;;;; Configuration utilities
(defun im-apply-patch-from-src-block (block-point-or-name target-folder)
"Apply the patch at src block BLOCK-POINT-OR-NAME to TARGET-FOLDER.
I keep some of my changes to packages as in patch format and this
simplifies applying those patches. I try to utilize advices most
of the time but this is for those times where advices either
complicates things or not sufficient."
(interactive (list (if-let (x (org-babel-where-is-src-block-head))
x
(save-excursion
(org-babel-goto-named-src-block (read-string "Block name: "))
(point)))))
(save-excursion
(if (stringp block-point-or-name)
(org-babel-goto-named-result block-point-or-name)
(goto-char block-point-or-name))
(let* ((block-content (org-element-property :value (org-element-at-point)))
(filename (make-temp-file "temp" nil ".patch" block-content))
(default-directory target-folder)
(patch-command (format "patch -p1 < %s" filename))
(patch-command-result (shell-command-to-string patch-command)))
(if (string-match-p "^patching file" patch-command-result)
(message "Patch applied successfully:\n%s" patch-command-result)
(error "Error applying patch:\n%s" patch-command-result)))))
(cl-defun im-tangle-file (&key doc path contents)
"Tangle CONTENTS into PATH.
DOC is simply for documentation, have no specific use. If CONTENTS has
a shebang at the beginning, then the executable bit is set to file."
(make-directory (file-name-directory path) t)
(write-region (concat contents "\n") nil path)
;; Make it executable if needed
(when (s-matches? "^[ \t]*#!" contents)
(set-file-modes path (file-modes-symbolic-to-number "+x" (file-modes path)))))
;;;;;; Elisp utils
(defmacro im-tap (form)
"Evaluate FORM and return its result.
Additionally, print a message to the *Messages* buffer showing
the form and its result.
This macro is useful for debugging and inspecting the
intermediate results of Elisp code without changing your code
structure. Just wrap the form with `im-tap' that you want to see
it's output without introducing an intermediate let-form."
`(let ((result ,form)
(print-length nil)
(print-level nil))
(message "[im-tap :: %s] → %s" ,(prin1-to-string form) result)
result))
(defalias 'im-inspect #'im-debug)
(defun im-debug (thing)
"Like `im-tap' but uses `pp-display-expression' to display the
result instead of `message'."
(let ((print-length nil)
(print-level nil))
(pp-display-expression thing "*im-debug*"))
thing)
(defmacro im-append! (lst item)
"Append ITEM to end of the LST.
Modifies LST. Only meant to be used in configuration."
`(setq ,lst (append ,lst (list ,item))))
(defun im-elisp-find-file-prefix ()
"Extract prefix from defgroup statement in current buffer.
I use this in my `defun' snippet via yasnippet."
(or (save-excursion
(goto-char (point-min))
(when (search-forward-regexp ":prefix \"\\(.*\\)\"" nil t)
(match-string 1)))
"im-"))
(defun im-open-region-in-temp-buffer (content)
"Open CONTENT (selected region or given string) in a temporary buffer."
(interactive (list (im-region-or 'string)))
(switch-to-buffer (generate-new-buffer "*temp-region*"))
(insert content)
(switch-to-buffer (current-buffer)))
(defun im-kill-this-buffer ()
"Kill current buffer.
Function `kill-this-buffer' does not work reliably. See
documentation of it."
(interactive)
(kill-buffer (current-buffer)))
(defun im-add-to-path (path)
"Add given PATH to PATH variable.
Useful for adding something to Emacs' PATH without restarting it."
(interactive "sPath: ")
(add-to-list 'exec-path (expand-file-name path))
(setenv "PATH" (concat (getenv "PATH") ":" (expand-file-name path))))
(defun im-get-reset-buffer (buffer)
"Create BUFFER and return it.
If it exists, it's killed first and return a new buffer."
(ignore-errors (kill-buffer buffer))
(get-buffer-create buffer))
;;;;;; Clipboard functions
(defun im-clipboard-contains-image-p ()
"Check whether the clipboard has image or not."
(cond
((locate-file "wl-paste" exec-path)
(s-contains? "image/" (shell-command-to-string "wl-paste --list-types")))
((locate-file "xclip" exec-path)
(s-contains? "image/" (im-sync-async-command-to-string "xclip" "-o" "-sel" "c" "-t" "TARGETS")))
((locate-file "pngpaste" exec-path)
(eq (shell-command "pngpaste - &>/dev/null") 0))))
(defun im-save-clipboard-image-to-file (file)
"Save the image in clipboard (if there is any) to given FILE.
Also see `im-clipboard-contains-image-p' to check if there is one."
(interactive "FFile to save the image: ")
(shell-command
(format "%s > %s"
(cond
((locate-file "wl-paste" exec-path) "wl-paste")
((locate-file "xclip" exec-path) "xclip -selection clipboard -target image/png -out")
((locate-file "pngpaste" exec-path) "pngpaste -"))
file)))
;;;;;; User input
(cl-defun im-get-input (&key (mode #'org-mode)
(init "")
on-accept
on-reject
pre-process)
"Display a buffer to user to enter some input."
(let* ((buffer (get-buffer-create "*im-input*"))
(success-handler (lambda ()
(interactive)
(let ((pre-proc-result (when pre-process
(with-current-buffer buffer
(funcall pre-process))))
(result (substring-no-properties (buffer-string))))
(kill-buffer buffer)
(if pre-process
(funcall on-accept result pre-proc-result)
(funcall on-accept result)))))
(reject-handler (lambda ()
(interactive)
(kill-buffer buffer)
(when on-reject
(funcall on-reject)))))
(switch-to-buffer buffer)
(with-current-buffer buffer
(funcall mode)
(use-local-map (copy-keymap (current-local-map)))
(local-set-key (kbd "C-c C-c") success-handler)
(local-set-key (kbd "C-c C-k") reject-handler)
(setq header-line-format "Hit `C-c C-c' to save `C-c C-k' to reject.")
(insert init))))
(defun im-alist-completing-read (prompt alist &optional initial)
"Like `completing-read' but returns value of the selected key in given ALIST."
(alist-get
(completing-read prompt alist nil nil initial)
alist nil nil #'equal))
(cl-defun im-completing-read
(prompt objects &key (formatter #'identity) category (sort? t) def multiple?)
"Provide an interactive completion interface for selecting an item from a list of objects.
- PROMPT: The prompt string to display to the user.
- OBJECTS: A list of objects to choose from.
- FORMATTER: (Optional) A function that formats each object
before displaying it to the user. The default is `'identity',
which means no formatting.
- CATEGORY: (Optional) A category symbol associated with the
completion. This can be used to provide additional completion
behavior.
- SORT?: (Optional) A boolean value indicating whether the
completion list should be sorted. The default is t.
- DEF: (Optional) The default value to return if no selection is
made. If multiple selections are allowed, this value will be
returned as a list.
- MULTIPLE?: (Optional) A boolean value indicating whether
multiple selections are allowed. The default is `nil`.
If MULTIPLE? is nil, this function returns the selected object
from the completion list. If MULTIPLE? is t, this function
returns a list of selected objects. If no selection is made, the
DEF value is returned."
(let* ((object-table
(make-hash-table :test 'equal :size (length objects)))
(object-strings
(mapcar
(lambda (object)
(let ((formatted-object (funcall formatter object)))
(puthash formatted-object object object-table)
(propertize formatted-object 'empv-item object)))
objects))
(selected
(funcall
(if multiple? #'completing-read-multiple #'completing-read)
(format "%s " prompt)
(lambda (string predicate action)
(if (eq action 'metadata)
`(metadata
,(when category (cons 'category category))
,@(unless sort?
'((display-sort-function . identity)
(cycle-sort-function . identity))))
(complete-with-action
action object-strings string predicate))))))
(if multiple?
(or (mapcar (lambda (it) (gethash it object-table)) selected) def)
(gethash selected object-table (or def selected)))))
(defun im-dmenu (prompt items &rest _ignored)
"Like `completing-read' but instead use dmenu.
Useful for system-wide scripts."
(with-temp-buffer
(thread-first
(cond
((functionp items)
(funcall items "" nil t))
((listp (car items))
(mapcar #'car items))
(t
items))
(string-join "\n")
string-trim
insert)
(shell-command-on-region
(point-min)
(point-max)
(im-when-on
:linux (format "rofi -dmenu -fuzzy -i -p '%s'" prompt)
:darwin "choose")
nil t "*im-dmenu error*" nil)
(string-trim (buffer-string))))
(cl-defmacro im-output-select
(&key cmd prompt keep-order
(formatter 'it)
(split "\n")
(drop 0)
(filter t)
(map 'it) (do 'it) category)
"Run given CMD and do a `completing-read' on it.
This macro is intended to quicken up the process of running a
shell command and doing a `completing-read' on it and then using
the result in another context, possibly on another shell
command."
`((lambda (it) ,do)
(im-completing-read
,prompt
(seq-filter
(lambda (it) ,filter)
(seq-map-indexed
(lambda (it idx) ,map)
(seq-drop
(s-split
,split
(shell-command-to-string ,cmd)
t)
,drop)))
:formatter (lambda (it) ,formatter)
:sort? ,(not keep-order)
:category ,category)))
(defun im-read-string (prompt &rest rest)
"Like `read-string' but returns `nil' on empty input."
(let ((result (string-trim (apply #'read-string prompt rest))))
(if (string-equal result "")
nil
result)))
;;;;;; String utils
;; Source: https://gist.github.com/jordonbiondo/c4e22b4289be130bc59b
(defmacro im-s-interpolated (str)
"Elisp string interpolation.
Uses #{elisp-code} syntax."
(let ((exprs nil))
(with-temp-buffer
(insert str)
(goto-char 1)
(while (re-search-forward "#{" nil t 1)
(let ((here (point))
(emptyp (eql (char-after) ?})))
(unless emptyp (push (read (buffer-substring (point) (progn (forward-sexp 1) (point)))) exprs))
(delete-region (- here 2) (progn (search-forward "}") (point)))
(unless emptyp (insert "%s"))
(ignore-errors (forward-char 1))))
(append (list 'format (buffer-string)) (reverse exprs)))))
(defun im-s-upcase-until (until s)
"Make prefix of a string S uppercase until given char UNTIL.
`(im-s-upcase-until \"-\" \"aha-hehe\")' -> \"AHA-hehe\""
(let ((end (s-index-of until s)))
(concat
(s-upcase (substring s 0 end))
(substring s end))))
(defun im-string-url-case (str)
"Convert STR to something like `a-string-appropriate-for-urls'.
>> (im-string-url-case \" test: test! şeyler ÜPPERCaSE vs.\")
=> \"test-test-seyler-uppercase-vs\""
(->>
str
downcase
(s-replace-all
'(("'" . "")
("ö" . "o")
("ı" . "i")
("ğ" . "g")
("ü" . "u")
("ş" . "s")
("ö" . "o")
("ç" . "c")))
(s-trim)
(replace-regexp-in-string "[^a-zA-Z0-9]" "-")
(replace-regexp-in-string "-+" "-")
(s-chop-prefix "-")
(s-chop-suffix "-")))
(defun im-human-readable-size (size-in-bytes)
(let* ((units '("B" "KB" "MB" "GB" "TB" "PB" "EB" "ZB" "YB"))
(unit (car units))
(bytes (float size-in-bytes))
(exponent (floor (log bytes 1024))))
(setq units (cdr units))
(while (> exponent 0)
(setq bytes (/ bytes 1024.0))
(setq exponent (1- exponent))
(setq unit (car units))
(setq units (cdr units)))
(format "%.2f %s" bytes unit)))
(defun im-non-blank-or-nil (x)
(if (and x (s-blank-str? x))
nil
x))
;;;;;; List/hash-table/vector utils
(defun im-hash-table-to-alist (val)
"Bad way to convert hash-tables with vectors into alists.
I use this only for debugging."
(cond
((hash-table-p val) (im-hash-table-to-alist (ht-to-alist val)))
((vectorp val) (mapcar #'im-hash-table-to-alist (cl-coerce val 'list)))
((json-alist-p val) (map-apply (lambda (key it) (cons key (im-hash-table-to-alist it))) val))
((listp val) (mapcar (lambda (key it) (cons key (im-hash-table-to-alist it))) val))
(t val)))
;;;;;; Quick table
(cl-defun im-output-to-tabulated-list (str &key buffer (sep " "))
(with-current-buffer buffer
(let* ((lines (s-split "\n" str t))
(header-items (s-split sep (car lines) t))
(header (cl-coerce (--map (list it (/ 100 (length header-items)) nil) header-items) 'vector))
(rows (thread-last lines
(-drop 1)
(--map-indexed (list (number-to-string it-index) (cl-coerce (s-split sep it t) 'vector))))))
(tabulated-list-mode)
(setq tabulated-list-format header)
(setq tabulated-list-entries rows)
(setq tabulated-list-padding 4)
(tabulated-list-init-header)
(tabulated-list-print t))
(switch-to-buffer buffer)))
;;;;;; UI utilities
(cl-defun im-insert-toggle-button (state1 state2 &key help on-toggle)
"Insert a button that change it's text from STATE1 to STATE2 when clicked.
HELP is displayed when cursor is on the button and
`im-help-at-point-mode' is enabled.
ON-TOGGLE is called when user toggles the button. It will be
called with the current state of the button."
(insert-text-button
(if (functionp state1) (funcall state1) state1) 'action
(lambda (button)
(let ((start (button-start button))
(end (button-end button))
(cursor (point)))
(delete-region start end)
(im-insert-toggle-button state2 state1 :help help :on-toggle on-toggle)
(goto-char (if (< cursor (+ start (length state2))) cursor start))
(when on-toggle
(funcall on-toggle state2))))
'kbd-help help
'follow-link t))
;;;;;; API call
;; This function is for doing easy REST calls and it uses plists for
;; everything because it's more readable and easier to type than
;; alists (but you can still use alists if you want or need to). I use
;; this to quickly prototype stuff in elisp.
(cl-defun im-request
(endpoint
&rest params
&key (-type "GET") (-headers) (-data) (-params) (-async?) (-on-success) (-on-error) (-raw)
&allow-other-keys)
"Like `request' but plist and JSON oriented. JSON responses are
automatically parsed, query parameters are constructed from
top-level keywords, request body can be a plist (which will be
serialized into JSON). Examples:
(im-request \"some/endpoint\")
With url parameters:
(im-request \"...\" :query \"test\" :page 3 :page_size 15)
If you want to pass an alist as url params:
(im-request \"...\" :-params \\='((query . \"test\") (page . 3) (page_size . 15)))
POST with json body:
(im-request \"...\" :-type \\='POST :-data \\='(:key1 1 :key2 2))
With some HTTP headers:
(im-request \"...\" :-headers \\='(:Authorization \"Bearer e21ewqfasdwtkl\"))
For async requests, simply provide a success handler:
(im-request \"...\"
:-on-success (cl-function
(lambda (&key data &allow-other-keys)
...use the parsed json DATA...)))"
(declare (indent defun))
(interactive (list (read-string "URL: ") :-raw t))
(let (json
(json-object-type 'alist)
(json-array-type #'list)
(json-key-type 'symbol))
;; Remove request related items from params list
(dolist (key '(:-type :-headers :-data :-params :-async? :-on-success :-raw :-on-error))
(cl-remf params key))
(let ((fn (lambda (resolve reject)
(request
endpoint
:type -type
:headers (cond
((and -headers (json-alist-p -headers)) -headers)
((and -headers (json-plist-p -headers)) (im-plist-to-alist -headers))
(t nil))
:parser (if -raw #'buffer-string (apply-partially #'json-parse-buffer :object-type 'alist :array-type 'list))
:success (cl-function
(lambda (&key data &allow-other-keys)
(funcall resolve data)))
:error (cl-function
(lambda (&key data status error-thrown &allow-other-keys)
(unless -on-error
(message "im-request :: failed status=%s, error-thrown=%s, data=%s" status error-thrown data))
(funcall reject data)))
:sync (and (not -on-success) (not -async?))
:data (cond
((and -data (json-alist-p -data)) (json-encode -data))
((and -data (json-plist-p -data)) (json-encode (im-plist-to-alist -data)))
((stringp -data) -data)
(t nil))
:params (cond
((and -params (json-alist-p -params)) -params)
((and -params (json-plist-p params)) (im-plist-to-alist -params))
(t (im-plist-to-alist params)))))))
(cond
(-async? (promise-new fn))
((or -on-success -on-error)
(funcall
fn
(or -on-success (lambda (data) (message "im-request :: Unhandled success. Data: %s" data)))
(or -on-error (lambda (data) (message "im-request :: Unhandled error. Data: %s" data)))))
(t (funcall fn (lambda (data) (setq json data)) (lambda (data) (user-error "Request failed, see earlier logs.")))
(when (called-interactively-p 'interactive)
(with-current-buffer (get-buffer-create "*im-request-response*")
(erase-buffer)
(insert json)
(json-pretty-print-buffer)
(json-ts-mode)