-
Notifications
You must be signed in to change notification settings - Fork 0
/
ocodo-handy-functions.el
2290 lines (1979 loc) · 81 KB
/
ocodo-handy-functions.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
;;; ocodo-handy-functions --- a collection of functions that didn't get organized
;;; Author: Jason Milkins <[email protected]>
;;; Commentary:
;;
;; A collection of miscellaneous functions and macros, which are either
;; candidates to migrate to a minor mode, or will languish here in perpetuity.
;;
;; Peppered in here are a few gems, some redundancies and some stuff I was just
;; playing with. They are auto-documented in this markdown document.
;;
;; Items used often:...
;;
;; - `current-buffer-defuns-to-markdown' (which generated this page.)
;; - `defun-pcase'
;; - `plist-bind'
;; - `*-and-replace'
;; - `screencapture-mac'
;; - `ocodo-custom-key-bindings-to-markdown'
;; - `format-multiline'
;;
;;; License:
;; GPL3
;;
;;; Code:
(require 'cl-lib)
(require 'cua-base)
(require 'cua-rect)
(require 'dash)
(require 'doom)
(require 'f)
(require 'find-func)
(require 'kurecolor)
(require 'kv)
(require 'all-the-icons)
(require 'lambda-line)
(require 'lisp-mnt)
(require 'magit)
(require 'markdown-soma)
(require 'multiple-cursors)
(require 'pcre2el)
(require 'projectile)
(require 'rx)
(require 'sh-script)
(require 'straight)
(require 'subr-x)
(require 'time-stamp)
(require 'xr)
(require 'yasnippet)
(defalias 'doom-reload 'doom/reload)
(defalias 'doom-increase-font-size 'doom/increase-font-size)
(defalias 'doom-decrease-font-size 'doom/decrease-font-size)
;; Declare used global vars
(defvar ocodo/markdown-faces-large
'((default 200)
(markdown-pre-face 200)
(markdown-language-keyword-face 200)
(markdown-code-face 200)
(markdown-table-face 200)
(markdown-header-face 300)
(markdown-header-face-1 300)
(markdown-header-face-2 280)
(markdown-header-face-3 260)
(markdown-header-face-4 250)
(markdown-header-face-5 230)
(markdown-header-face-6 210))
"List of default and markdown faces, For text scaling in markdown.
Large monitor sizing.")
(defvar ocodo/markdown-faces-desktop
'((default 150)
(markdown-pre-face 150)
(markdown-language-keyword-face 150)
(markdown-code-face 150)
(markdown-table-face 150)
(markdown-header-face 250)
(markdown-header-face-1 250)
(markdown-header-face-2 230)
(markdown-header-face-3 210)
(markdown-header-face-4 200)
(markdown-header-face-5 180)
(markdown-header-face-6 160))
"List of default and markdown faces, For text scaling in markdown.
Desktop monitor sizing.")
(defvar ocodo/markdown-faces
(if (eq system-type 'darwin)
;; I only use Macs on large screens/TVs at the moment
ocodo/markdown-faces-large
ocodo/markdown-faces-desktop)
"List of markdown and default faces.
Used for text scaling in markdown.")
(defvar recentf-list)
(defvar smie-config)
(defvar sh-styles-alist)
(defvar ocodo-github-repos-cache '()
"Cache list of github repos.")
(defvar ocodo-github-orgs (list
"ocodo"
"emacsfodder"
"codefodder"
"osxfodder"
"getclacking"
"emacsgifs"
"gofodder"
"cutbox"
"crystal-castles"
"nms-shoppinglist")
"List of my active github orgs.")
(defmacro let1 (var val &rest body)
"Syntax sugar for LET. A single VAR VAL let over BODY.
Example usage:
```lisp
(let1 my-var \"Hello World\"
(message \"%s\" my-var))
=> \"Hello World\"
```"
`(let ((,var ,val)) ,@body))
(defmacro plist-bind (args expr &rest body)
"Destructure PLIST, ARGS (keys) of EXPR (a plist) are available in BODY.
For example:
```lisp
(plist-bind (a c) ;; <- arg names match key names.
\='(:a \"foo\" :b 13 :c \"bar\") ;; <- plist
(list a c)) ;; <- Body
;; => (\"foo\" \"bar\")
```"
`(cl-destructuring-bind
(&key ,@args &allow-other-keys)
,expr
,@body))
(defmacro when-gui (&rest body)
"Evaluate BODY only if Emacs has a GUI."
`(when (display-graphic-p) ,@body))
(defun -sample (list)
"Return a random element from the LIST."
(nth (random (length list)) list))
(defmacro *-and-replace (name evaluator)
"Create a command NAME which replace region with result of EVALUATOR.
For example:
Using `shell-command-to-string', we can make a replace-region
command with `*-and-replace'
```lisp
(*-and-replace shell-command-eval-and-replace #\='shell-command-to-string)
;; =>
;; (shell-command-eval-and-replace)
```"
`(defun ,name ()
(interactive)
(if (not (region-active-p))
(replace-thing-at-point-with ,evaluator)
(replace-region-with ,evaluator))))
(*-and-replace calc-eval-replace-at-region-or-point #'calc-eval)
(*-and-replace decimal-to-hex-at-point-or-region #'decimal-to-hex)
(*-and-replace eval-regexp-to-rx-replace #'xr)
(*-and-replace hex-to-decimal-at-point-or-region #'hex-to-decimal)
(*-and-replace replace-md-code-with-docstring-arg-in-region #'md-code-to-docstring-arg)
(*-and-replace time-to-seconds-at-point-or-region #'time-to-seconds)
(*-and-replace markdown-literate-wrap-exec-code
#'(lambda (region) (format-multiline "|``` @code
|%s
|```" region)))
(defmacro defun-pcase (name arglist &optional docstring &rest body)
"Define a pcase function called NAME with ARGLIST.
While `&optional' all `defun-pcase' should have a DOCSTRING.
BODY is the form of the underlying `pcase-lambda'.
These are very useful for certain destructuring / cherry picking
operations on lists / trees.
For example:
```lisp
(defun-pcase pick-it (\=`(,_ ,_ (,_ ,it ,_)))
\"Select it\"
(format \"%s\" it))
(my-pfun \='(1 2 (1 \"this one\" 3)))
;; => \"this one\"
```"
(declare (doc-string 3) (indent 2))
`(progn (defalias
(quote ,name)
(pcase-lambda ,arglist ,@body)
,docstring)))
(defvar screencapture-mac-default-commandline nil
"Default command line with options.")
(defvar screencapture-mac-default-file-location
(expand-file-name "~/Desktop/")
"Default location to save screen captures.")
(defvar screencapture-mac-default-file-keyword
"screencapture")
(defun align-number-right (begin end)
"Align columns of numbers right in the region (BEGIN, END).
For example:
```
10 49 1123
301 213 4111
2134 4151 525235
48912 522 19538
;; =>
;; 10 49 1123
;; 301 213 4111
;; 2134 4151 525235
;; 48912 522 19538
```"
(interactive "r")
(align-regexp begin end ".* \\([0-9]+\\).*" -1 1 nil))
(defun buffer-file-name-to-kill-ring ()
"Save the buffer file name to the kill ring."
(interactive)
(when (buffer-file-name)
(kill-new (buffer-file-name))))
(defun change-number-at-point (func)
"Change the number at point using FUNC.
It should be wrapped in an interactive function, and func should
take a single numeric argument and return anything.
For example:
```lisp
(defun round-number-at-point ()
\"Round the number at point.\"
(interactive)
(change-number-at-point #\='round))
;; Or...
(defun number-at-point-to-currency ()
\"Change the number at point to currency.\"
(format \"$%.2f\" (number-at-point))))
```"
(let ((number (number-at-point))
(point (point)))
(when number
(progn
(forward-word)
(search-backward (number-to-string number))
(replace-match (number-to-string (funcall func number)))
(goto-char point)))))
(defun chmod-this-file (mode)
"Change the permissions of the current buffer's file to MODE.
MODE is a string representing the new permissions, e.g. \"755\"."
(interactive "sEnter new permissions (e.g. 755): ")
(when buffer-file-name
(let ((filename (buffer-file-name)))
(shell-command (concat "chmod " mode " " filename))
(message "Changed permissions of %s to %s." filename mode))))
(defun chmod-executable-this-file ()
"Change the permissions of the current buffer's file to make it executable."
(interactive)
(when buffer-file-name
(let ((filename (buffer-file-name)))
(shell-command (concat "chmod +x " filename))
(message "Changed permissions of %s to executable." filename))))
(defun cleanup-buffer ()
"Cleanup buffer, tabs to spaces, re-indent, trim whitespace."
(interactive)
(indent-buffer)
(untabify-buffer)
(delete-trailing-whitespace))
(defun clear-buffer-text-properties ()
"Clear all text face properties in the buffer.
This is somewhat useful when dealing with text pasted from a
propertied buffer.
Note: this won't turn off face properties in a font-locked buffer."
(interactive)
(remove-text-properties 1 (point-max) '(face nil)))
(defun comment-or-uncomment-current-line-or-region ()
"Comments or uncomments the current line or all the lines in region."
(interactive)
(save-excursion
(let (min max)
(if (region-active-p)
(setq min (region-beginning) max (region-end))
(setq min (point) max (point)))
(comment-or-uncomment-region
(progn (goto-char min) (line-beginning-position))
(progn (goto-char max) (line-end-position))))))
(defun copy-region-or-rest-of-line-to-other-window ()
"Copy the current region to the other window."
(interactive)
(if (region-active-p)
(kill-ring-save (region-beginning) (region-end))
(copy-rest-of-line))
(other-window 1)
(yank))
(defun copy-rest-of-line ()
"Copy from cursor to end the current line to the kill ring."
(interactive)
(save-mark-and-excursion
(cua-set-mark)
(move-end-of-line 1)
(kill-ring-save nil nil t)))
(defun copy-whole-line ()
"Copy the current line to the kill ring."
(interactive)
(save-mark-and-excursion
(move-beginning-of-line 1)
(cua-set-mark)
(move-end-of-line 1)
(kill-ring-save nil nil t)))
(defun csv-to-lists (csv)
"Convert simple (very limited) CSV string to list of lists.
Consider this a basic experiment, which won't be developed.
Use `csv-mode` instead.
For example:
```lisp
(let1 csv (format-multiline
\"|1, 2, 3, Words like this, #ffeeff
|2, 41, 414, 2002, Foo Bar\")
(csv-to-lists csv))
;; => ((\"1\" \"2\" \"3\" \"Words like this\" \"#ffeeff\")
;; (\"2\" \"41\" \"414\" \"2002\" \"Foo Bar\"))
```"
(mapcar (lambda (line) (split-string line ","))
(split-string (s-chomp csv) "\n")))
(require 'which-key)
(defun cua-rectangle-which-key-help ()
"Display cua-rectangle-keymap in which-key."
(interactive)
(which-key-show-keymap 'cua--rectangle-keymap
cua--rectangle-keymap))
(defun decimal-to-hex (num)
"Convert NUM to hex."
(format "%X" (string-to-number num)))
(defun decrease-default-font-height (m)
"Adjust the default font :height by 10 (prefix arg M for multiples)."
(interactive "p")
(if (display-graphic-p)
(increase-default-font-height -1)
(message "GUI only")))
(defun decrement-number-at-point ()
"Decrement number at point like vim's Ctrl x."
(interactive)
(change-number-at-point '1-))
(defun delete-frame-or-window-dwim ()
"Delete the current frame or buffer.
When there is only one frame, kill the buffer."
(interactive)
(if (> 1 (length (frame-list)))
(delete-frame)
(kill-buffer)))
(defun delete-this-buffer-and-file (force)
"Delete kill file and buffer, prefix arg FORCE."
(interactive "P")
(let ((filename (buffer-file-name))
(buffer (current-buffer))
(name (buffer-name)))
(if (not (and filename (file-exists-p filename)))
(error "'%s' is not a file buffer" name)
(when (or force (yes-or-no-p (format "Delete '%s', Are you sure? " filename)))
(delete-file filename)
(kill-buffer buffer)
(message "Deleted '%s'" filename)))))
(defun describe-thing-at-point ()
"Describe the function or variable at point."
(interactive)
(let* ((thing (symbol-at-point)))
(cond
((fboundp thing) (describe-function thing))
((boundp thing) (describe-variable thing)))))
(defun describe-char-here-untouched ()
"Describe the char at point, but first move the point away.
Move back to point after describing the char."
(interactive)
(let ((p (point)))
(if (= (point-min) p)
(goto-char (point-max))
(goto-char (point-min)))
(describe-char p)
(goto-char p)))
(defun describe-char-next (prefix)
"Describe the char next to point (+1).
Universal PREFIX can be used to describe char
at N positons from `point'."
(interactive "p")
(let ((p (point)))
(describe-char (+ p prefix))))
(defun describe-char-previous (prefix)
"Describe the char previous from point (-1).
Universal PREFIX can be used to describe char
at N positons from `point'."
(interactive "p")
(let ((p (point)))
(describe-char (- p prefix))))
(defun dired-find-file-other-window-and-back ()
"Open file or directory, focus original window."
(interactive)
(find-file-other-window (dired-get-file-for-visit))
(other-window -1))
(defun dired-menu ()
"Go to one of the currently open Dired buffers (if there is one)."
(interactive)
(let* ((dired-buffers (--map (buffer-name it)
(--filter
(equal 'dired-mode (with-current-buffer it major-mode))
(buffer-list)))))
(if dired-buffers
(switch-to-buffer (completing-read "Select dired: " dired-buffers))
(message "There's no dired buffers open right now"))))
(defun dired-osx-open-this-file ()
"Use the OSX `open' command to launch the current Dired file at point."
(interactive)
(shell-command-to-string (format "open %S" (dired-file-name-at-point))))
(defun dired-visit-library (libraryname)
"Open directory with Dired which contain the given LIBRARYNAME."
(interactive "M")
(dired (file-name-as-directory
(file-name-directory (find-library-name libraryname)))))
(defun duplicate-current-line-or-region (arg &optional up)
;; Originally swiped from rejeep's emacs.d rejeep-defuns.el.
"Duplicates the current line or region ARG times.
If UP is non-nil, duplicate and move point to the top."
(interactive "p")
(let (beg
end
(origin (point))
(saved-region
(when (use-region-p) (list (region-beginning) (region-end)))))
(if (and (use-region-p) (> (point) (mark)))
(exchange-point-and-mark))
(setq beg (line-beginning-position))
(if (use-region-p)
(exchange-point-and-mark))
(setq end (line-end-position))
(let ((region (buffer-substring-no-properties beg end)))
(dotimes (i arg)
(goto-char end)
(newline)
(insert region)
(setq end (point)))
(if up
(goto-char origin)
(goto-char (+ origin (* (length region) arg) arg)))
(when saved-region
(if up
(progn (message "setting region (up)")
(push-mark-command nil)
(goto-char (nth 1 saved-region))
(exchange-point-and-mark))
(progn (message "setting region")
(push-mark-command nil)
(goto-char (- (point) (length region)))))
(setq deactivate-mark nil)))))
(defun duplicate-current-line-or-region-up (arg)
"Duplicates the current line or region up ARG times."
(interactive "p")
(duplicate-current-line-or-region arg t))
(defun eval-and-replace ()
"Replace the preceding sexp with its result."
(interactive)
(backward-kill-sexp)
(condition-case nil
(insert (format "%s" (eval (read (current-kill 0)))))
(error (message "Invalid expression")
(insert (current-kill 0)))))
(defun eval-and-replace-prin1 ()
"Replace the preceding sexp with its value using prin1."
(interactive)
(backward-kill-sexp)
(condition-case nil
(prin1 (eval (read (current-kill 0)))
(current-buffer))
(error (message "Invalid expression")
(insert (current-kill 0)))))
(defun filter-recentf (pattern)
"Remove entries matching PATTERN from recent files.
This is operating on the `recentf-list', in memory.
Use `recentf-save-list' to persist."
(interactive "MRemove recentf entries mathing pattern: ")
(let ((temporary-recentf-list
(--reject (s-matches-p pattern it) recentf-list)))
(setq recentf-list temporary-recentf-list)))
(defun flush-blank-lines ()
"Flush blank lines."
(interactive)
(flush-lines "^\s*$" nil nil t))
(defun format-binary (val &optional width)
"Convert VAL of WIDTH to a binary string.
&optional WIDTH will default to 8."
(let* ((w (or width 8))
(binary (int-to-binary-string val)))
(message "Width: %d" w)
(s-pad-left w "0" binary)))
(defun format-multiline (format-string &rest args)
"Format a multiline indented FORMAT-STRING with ARGS.
A multiline string can use leading `|` (pipe) characters to line
up indentation.
ARGS passed will populate format template tokens in the
FORMAT-STRING. Tokens are as defined in `(format ...)`
For example:
```
(fomat-multiline \"|- List...
| - Item %s
| - Item %#x
| - Item %x
|
|... %s\"
\"one\" 2 #xf \"the end\")
=>
\"- List...
- Item one
- Item 0x2
- Item f
... the end\"
```"
(apply 'format
(s-join "\n" (--map (s-replace-regexp "^\s*|" "" it) (s-lines format-string)))
args))
(defun duplicate-sexp (arg)
"Duplicate sexp, follows the ARG rules of `kill-sexp'."
(interactive "p")
(kill-sexp arg)
(yank)
(yank))
(defun kill-save-sexp (arg)
"Save sexp to `kill-ring', follows the ARG rules of `kill-sexp'."
(interactive "p")
(kill-sexp arg)
(yank))
(defun format-thousands-separators (n)
"Format N to have thousand separators.
For example:
```lisp
(format-thousands-separators 3032498000)
;; => \"3,032,498,000\"
```"
(let* ((parts (split-string (number-to-string n) "[.]"))
(characteristic (car parts))
(separated
(reverse
(string-join (--reject (string= it "")
(split-string (replace-regexp-in-string
"[0-9]\\{3\\}"
"\\& "
(reverse characteristic))
" "))
","))))
(if (eq (length parts) 1)
separated
(format "%s.%s" separated (nth 1 parts)))))
(defun fraction-radian (denominator)
"Fraction DENOMINATOR of circle to radians."
(interactive "nDenomiator:")
(insert (format "%s" (/ (* float-pi 2) denominator))))
(defun generate-untitled-name ()
"Generate a name with pattern untitled-n."
(let ((n 1))
(while
(member (format "untitled-%i" n)
(mapcar
(lambda (it) (buffer-name it))
(buffer-list)))
(setq n (+ n 1)))
(format "untitled-%i" n)))
(defun get-osx-display-resolution ()
"Get the current display resolution in OSX.
Uses the mac system_profiler `SPDisplaysDataType' to lookup the
current display resolution. This is then filtered out (using grep
& perl) and formattted to a list of `(w h)'.
For example:
```lisp
(get-osx-display-resolution)
;; => (\"3840\" \"2160\")
```"
(s-split "x"
(s-chomp
(shell-command-to-string
"system_profiler SPDisplaysDataType |\
grep Resolution |\
perl -pe \
's/^ *Resolution: ([0-9]+? x [0-9]+?) .*$/\\1/' |\
tr -d ' '"))))
(defun get-position-of-nearest-matching (s &optional arg)
"Get the position of nearest S.
optional ARG when less than zero, default to the before match
when matches are equidistant from the current point."
(let* ((after (- (save-excursion (search-forward s)) (length s)))
(before (save-excursion (search-backward s)))
(dist-after (- after (point)))
(dist-before (- (point) before)))
(if (eq dist-after dist-before)
(if (and arg (>= 0 arg)) after before)
(if (< dist-after dist-before)
after
before))))
(defun get-position-of-nearest-regexp-match (regexp &optional arg)
"Get the position of nearest REGEXP match.
optional ARG when less than zero, default to the before match
when matches are equidistant from the current point."
(let* ((after (save-excursion (search-forward-regexp regexp)))
(before (save-excursion (search-backward-regexp regexp)))
(dist-after (- after (point)))
(dist-before (- (point) before)))
(if (eq dist-after dist-before)
(if (and arg (>= 0 arg)) after before)
(if (< dist-after dist-before)
after
before))))
(defun git-open-changed-and-new-files ()
"Use git ls-files to open changed files."
(interactive)
(let ((git-modified-files (shell-command-to-string "git ls-files -m --others --exclude-standard")))
(if (not (string-match "^fatal: Not a git repo" git-modified-files))
(let ((file-list (split-string git-modified-files "\n" t "[\r\n\t ]")))
(mapc (lambda (file) (find-file file)) file-list))
(user-error "Not in a git repository"))))
(defun git-open-changed-files ()
"Use git ls-files to open changed files."
(interactive)
(let ((git-modified-files (shell-command-to-string "git ls-files -m")))
(if (not (string-match "^fatal: Not a git repo" git-modified-files))
(let ((file-list (split-string git-modified-files "\n" t "[\r\n\t ]")))
(mapc (lambda (file) (find-file file)) file-list))
(user-error "Not in a git repository"))))
(defun git-open-from-ls-files (git-ls-options)
"Use GIT-LS-OPTIONS to open changed files."
(interactive "sGit ls-files options: ")
(let ((git-modified-files (shell-command-to-string (format "git ls-files %s" git-ls-options))))
(if (not (string-match "^fatal: Not a git repo" git-modified-files))
(let ((file-list (split-string git-modified-files "\n" t "[\r\n\t ]")))
(mapc (lambda (file) (find-file file)) file-list))
(user-error "Not in a git repository"))))
(defun git-open-ls-files (git-ls-options)
"Use GIT-LS-OPTIONS to open changed files."
(interactive (list
(completing-read "Open changed files: " '("--modified"
"--other --exclude-standard"
"--other --exclude-standard --modified"
"--unmerged"
"--ignored"))))
(let ((git-modified-files (shell-command-to-string (format "git ls-files %s" git-ls-options))))
(if (not (string-match "^fatal: Not a git repo" git-modified-files))
(let ((file-list (split-string git-modified-files "\n" t "[\r\n\t ]")))
(if (> 0 (length file-list))
(mapc (lambda (file) (find-file file)) file-list)
(message "No files to open")))
(user-error "Not in a git repository"))))
(defun git-open-untracked-files ()
"Use git ls-files to open untracked files.
Open any untracked file in the repo (unless it's been .gitignored)"
(interactive)
(let ((git-untracked-files (shell-command-to-string "git ls-files --others --exclude-standard")))
(if (not (string-match "^fatal: Not a git repo" git-untracked-files))
(let ((file-list (split-string git-untracked-files "\n" t "[\r\n\t ]")))
(mapc (lambda (file) (find-file file)) file-list))
(user-error "Not in a git repository"))))
(defun git-in-repo-p (dir)
"True if DIR is in a git repo."
(not (string-match "^fatal: Not a git repo " (shell-command-to-string "git ls-files"))))
(defun git-delete-file-from-cache (filename)
"Git rm --cache FILENAME."
(interactive "f")
(shell-command (format "git rm --cache %s" filename)))
(defun ocodo-github-repos ()
"List github repos using gh cli and `ocodo-github-orgs'."
(unless ocodo-github-repos-cache
(setq ocodo-github-repos-cache
(s-split "\n"
(s-join ""
(--map
(shell-command-to-string
(format "gh repo list %s --json nameWithOwner -t '{{range .}}{{tablerow .nameWithOwner}}{{end}}'" it))
ocodo-github-orgs))
t)))
ocodo-github-repos-cache)
(defun ocodo-github-repos-refresh ()
"Refresh repos cache."
(interactive)
(setq ocodo-github-repos-cache nil)
(ocodo-github-repos))
(defun ocodo/resize-frame (width-pixels height-pixels top-x-pixel top-y-pixel)
"Resize current frame to WIDTH-PIXELS, HEIGHT-PIXELS, TOP-X-PIXEL & TOP-Y-PIXEL."
(interactive
(list
(read-number "Frame width (px): " (display-pixel-width))
(read-number "Frame height (px): " (display-pixel-height))
(read-number "Frame x: " 0)
(read-number "Frame y: " 0)))
(set-frame-size nil width-pixels height-pixels t)
(set-frame-position nil top-x-pixel top-y-pixel))
(defun ocodo/resize-frame-maximized ()
"Resize current frame to screen maximum size."
(interactive)
(let ((width (display-pixel-width))
(height (display-pixel-height))
(x 0)
(y 0))
(ocodo/resize-frame width height x y)))
(defun ocodo/resize-frame-inset-maximized (px)
"Resize current frame to screen maximum size inset by PX."
(interactive "nInset px: ")
(let ((width (- (display-pixel-width) (* 2 px)))
(height (- (display-pixel-height) (* 2 px)))
(x (+ 0 px))
(y (+ 0 px)))
(ocodo/resize-frame width height x y)))
(defun ocodo/gist-create ()
"Comments or uncomments the current line or all the lines in region."
(interactive)
(save-excursion
(let (min max)
(if (region-active-p)
(setq min (region-beginning) max (region-end))
(setq min (point-min) max (point-max)))
(shell-command-on-region min max
(format "gh gist create --desc '%s' --filename '%s' %s"
(string-replace "'" "\\'" (read-string "Gist Description: " nil nil "TODO Description"))
(read-string "Gist Filename: " (file-name-nondirectory (buffer-file-name)) nil "untitled")
(when (y-or-n-p "Public Gist ?") "--public"))))))
(defun ocodo/goals-create-github-issues (goals-markdown-file)
"Read GOALS-MARKDOWN-FILE and create issues from its top level tasks.
Sub-tasks are added to the issue body."
(interactive "fSelect goals.md: ")
(shell-command "gh "))
(defun ocodo-open-project (project)
"Open a PROJECT in workspace or from github."
(interactive (list (completing-read "Select a project: " (ocodo-project-list))))
(if (string-match-p "git@github\\.com:" project)
(ocodo-open-project-repo-locally project)
(ocodo-open-local-project project)))
(defun ocodo-open-project-repo-locally (project)
"Open a PROJECT repo locally.
Clone if not already in workspace."
(let ((path (ocodo-find-local-repo project)))
(if path
(ocodo-open-local-project path)
(progn
(let ((path (format "~/workspace/%s" (f-filename project))))
(if (f-exists-p path)
(error "%s already exists" path)
(progn
(ocodo-clone-project project path)
(ocodo-open-local-project path))))))))
(defun ocodo-clone-project (project path)
"Clone PROJECT (git ssh url) to PATH."
(message
(shell-command-to-string (format "git clone %s %s" project path))))
(defun ocodo/bump-version-patch ()
"Search for version and increment the patch number of the string editor macro."
(interactive)
(goto-char 0)
(search-forward "version =")
(end-of-line)
(search-backward ".")
(insert " ")
(forward-char 1)
(increment-number-at-point)
(search-backward ".")
(delete-horizontal-space))
(defun ocodo/get-filename-size ()
"Get the size of filename at the current line.
Only works with lines which contain a filename."
(interactive)
(let* ((name (s-chomp (thing-at-point 'line)))
(size (f-size name)))
(message "%s"
(file-size-human-readable (f-size name)))))
(defun ocodo/find-filename ()
"Open the filename at the current line in Emacs."
(interactive)
(let* ((name (s-chomp (thing-at-point 'line))))
(find-file name)))
(defun ocodo/mac-open-filename ()
"Open the filename at the current line with Macos open command."
(interactive)
(let* ((name (s-chomp (thing-at-point 'line))))
(message (shell-command-to-string (format "open \"%s\"" name)))))
(defun ocodo/git-pull-and-push ()
"Do git pull --rebase --autostash && git push on the current directory."
(interactive)
(async-shell-command "git pull --rebase --autostash && git push"))
(defun ocodo/git-remote-url (&optional directory remote)
"Return the url of the git REMOTE in DIRECTORY.
Return nil if no remote or not a git repo.
DIRECTORY and REMOTE are optional.
Current dir and origin will be used by default."
(let ((directory (if directory (format "-C %s" directory) ""))
(remote (or remote "origin")))
(s-chomp (shell-command-to-string (format "git %s remote get-url %s" directory remote)))))
(defun ocodo/write-region ()
"If a region is marked, write it to a new file.
If not, write the whole buffer to a new file"
(interactive)
(if (region-active-p)
(call-interactively #'write-region)
(save-mark-and-excursion
(call-interactively #'mark-whole-buffer)
(call-interactively #'write-region))))
(defun ocodo-find-local-repo (project)
"Return the path of PROJECT with repo url.
Look for name matches in workspace, Check git remote for a match."
(let ((workspace-folders (cl-copy-list (ocodo-local-project-list)))
(found nil))
(while (and (null found) workspace-folders)
(let* ((d (car workspace-folders))
(url (ocodo/git-remote-url d)))
(when (string= url project) d (setq found d))
(setq workspace-folders (cdr workspace-folders))))
found))
(defun ocodo-project-list ()
"List of project names from workspace and github repos."
(append
(mapcar
(lambda (p) (format "[email protected]:%s.git" p))
(ocodo-github-repos))
(ocodo-local-project-list)))
(defun ocodo-local-project-list ()
"List of project names from workspace."
(f-directories "~/workspace"))
(defun ocodo-open-local-project (project)
"Open a local PROJECT."
(if (f-exists-p project)
(find-file project)
(error "%s was not found locally" project)))
(defun github-browse-current-repo (repo)
"Browse the current github REPO.
If the user is not in a repo, Select from `ocodo-github-repos'."
(interactive (list
(if (git-in-repo-p (pwd))
(s-chomp (shell-command-to-string "gh repo view --json nameWithOwner -t '{{tablerow .nameWithOwner}}'"))
(completing-read "Github Repo [format: user/repo]: " (ocodo-github-repos) nil nil))))
(browse-url (format "https://github.com/%s" repo)))
(defun github-browse-repo (repo)
"Browse the github REPO. Select from `ocodo-github-repos'."
(interactive (list (completing-read "Github Repo [format: user/repo]: " (ocodo-github-repos) nil nil)))
(browse-url (format "https://github.com/%s" repo)))
(defun google-en-to-thai (text)
"Translate TEXT from English to Thai."
(let* ((response-json
(shell-command-to-string
(format "curl -s \"https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=th&dt=t&q=%s\""
(url-hexify-string text))))
(translation (replace-regexp-in-string "\\[+\"\\(.*?\\)\".*$" "\\1" response-json)))
translation))
(defun google-en-to-thai-on-region (begin end)
"Translate english in region (BEGIN END) to Thai."
(interactive "r")
(let* ((text (buffer-substring begin end))
(translated (google-en-to-thai text)))
(message translated)))
(defun hex-to-decimal (num)
"Convert hex NUM to decimal."
(format "%i" (string-to-number num 16)))
(defun increase-default-font-height (prefix)
"Adjust the default font :height by 10, PREFIX (to set by multiples)."
(interactive "p")
(if (display-graphic-p)
(let ((new-height (+ (* prefix 10) (face-attribute 'default :height))))
(set-face-attribute 'default nil :height new-height)
(message "Default font height set to %i" new-height))
(message "GUI only")))
(defun increment-number-at-point ()
"Increment number at point like vim's Ctrl a."
(interactive)
(change-number-at-point '1+))
(defun increment-number-binary (&optional arg)