-
Notifications
You must be signed in to change notification settings - Fork 20
/
worf.el
executable file
·2053 lines (1859 loc) · 71.9 KB
/
worf.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
;;; worf.el --- A warrior does not press so many keys! (in org-mode)
;; Copyright (C) 2014-2020 Oleh Krehel
;; Author: Oleh Krehel <[email protected]>
;; URL: https://github.com/abo-abo/worf
;; Version: 0.1.0
;; Package-Requires: ((swiper "0.11.0") (ace-link "0.1.0") (hydra "0.13.0") (zoutline "0.1.0"))
;; Keywords: lisp
;; This file is not part of GNU Emacs
;; This file 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, 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.
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; This extension works similar to http://orgmode.org/manual/Speed-keys.html,
;; while adding in a bit of vi flavor.
;;
;; Representing the point with "|", pressing a-z, A-Z, or 0-9 while
;; the text is as below will call a command instead of inserting these
;; characters:
;;
;; |* foo
;; *|* bar
;; |#+ baz
;;
;; As you see, the general theme is beginning of line + org markup.
;; Below, "#+..." will be referred to as markup.
;; Similar to vi, "hjkl" represent the arrow keys:
;;
;; - "j" moves down across headings and markup, but does not switch
;; between either: use "h"/"l" for that. The exception is the first
;; markup in the file that does not belong to any heading.
;;
;; - "k" moves up across headings and markup, with same rules as "j".
;;
;; - "h" moves left, i.e. to the parent heading of current thing.
;; You can use it e.g. to go from fifth level 3 heading to the
;; parent level 2 heading, or from the second source block to the
;; parent heading.
;;
;; - "l" moves right (i.e. to the first child of current heading).
;; You can use it to get to the first markup of current heading.
;;
;; Worf borrows the idea of verbs and nouns from vi: the commands are
;; sentences, combinations of a verb and a noun used together.
;; Verb #1 is "goto", which is implicit and active by default.
;;
;; 5 nouns are available currently:
;; "h" - left
;; "j" - down
;; "k" - up
;; "l" - right
;; "a" - add heading
;; "p" - property
;;
;; Verb #2 is `worf-change-mode', bound to "c". Verbs in worf are
;; sticky: once you press "c", change verb will be active until you
;; switch to a different verb. This is different from vi, where the
;; verb will deactivate itself after the first command.
;;
;; Use the same letter to deactivate a verb as to activate it,
;; i.e. "c" will deactivate `worf-change-mode'. "q" will universally
;; deactivate any verb and return you to "goto" implicit verb.
;;
;; While `worf-change-mode' is active, "hjkl" move the current heading
;; in appropriate directions: it's the same as holding "M-" and using
;; arrow keys in the default org.
;; "p" will change the selected property.
;;
;; Verb #3 is `worf-change-tree-mode', bound to "cf". While
;; `worf-change-tree-mode' is active, "hjkl" move the current heading
;; tree in appropriate directions: it's the same as holding "S-M-" and
;; using arrow keys in the default org.
;;
;; Verb #4 is `worf-change-shift-mode', bound to "cs".
;; It make "hjkl" act as "S-" and arrows in default org.
;;
;; Verb #5 is `worf-keyword-mode', bound to "w". You select a keyword
;; e.g. TODO or NEXT and "j"/"k" move just by the selected keyword,
;; skipping all other headings. Additionally "a" will add a new
;; heading with the appropriate keyword, e.g. "wta" will add a new
;; TODO, and "wna" will add a new "NEXT".
;;
;; Verb #6 is `worf-clock-mode', bound to "C". This one isn't sticky
;; and has only two nouns that work with it "i" (in) and "o" (out).
;;
;; Verb #7 is `worf-delete-mode', bound to "d". This one isn't sticky
;; and changes the behavior of "j" to delete down, and "k" to delete
;; up. You can mix in numbers to delete many times, i.e. d3j will
;; delete 3 headings at once.
;; "p" will delete the selected property.
;;
;; Verb #8 is `worf-yank-mode', bound to "y". It's similar to
;; `worf-delete-mode', but will copy the headings into the kill ring
;; instead of deleting.
;;
;; Verb #9 is `worf-mark-mode', bound to "m". It's similar to
;; `worf-delete-mode', but will mark the headings instead.
;;
;; Some other things included in worf, that don't fit into the
;; verb-noun structure, are:
;;
;; - "o" (`worf-ace-link'): open a link within current heading that's
;; visible on screen. See https://github.com/abo-abo/ace-link for a
;; package that uses this method in other modes.
;;
;; - "g" (`worf-goto'): select an outline in the current buffer, with
;; completion. It's very good when you want to search/navigate to
;; a heading by word or level. See https://github.com/abo-abo/lispy
;; for a package that uses this method to navigate Lisp code.
;;
;; - "L" (`worf-copy-heading-id'): copy the link to current heading
;; to the kill ring. This may be useful when you want to create a
;; lot of links.
;;
;;; Code:
;; ——— Requires ————————————————————————————————————————————————————————————————
(require 'ace-link)
(require 'dired)
(require 'flyspell)
(require 'org)
(require 'org-agenda)
(require 'org-attach)
(require 'org-capture)
(require 'org-clock)
(require 'org-element)
(require 'org-id)
(require 'swiper)
(require 'zoutline)
(defgroup worf nil
"Navigate Org-mode with plain keys."
:group 'org
:prefix "worf-")
;; ——— Minor mode ——————————————————————————————————————————————————————————————
(defvar worf-sharp "^#\\+"
"Shortcut for the org's #+ regex.")
(defvar worf-regex "^\\(?:\\*\\|#\\+\\)"
"Shortcut for worf's special regex.")
(defvar worf-regex-full "^\\(?:\\*+ \\|#\\+\\|:\\)"
"Shortcut for worf's special regex.")
(defvar worf-mode-map
(make-sparse-keymap))
;;;###autoload
(define-minor-mode worf-mode
"Minor mode for navigating and editing `org-mode' files.
When `worf-mode' is on, various unprefixed keys call commands
if the (looking-back \"^*+\") is true.
\\{worf-mode-map}"
:group 'worf
:lighter " ✇"
(if worf-mode
(advice-add 'org-current-effective-time
:around #'worf--current-effective-time)
(advice-remove 'org-current-effective-time #'worf--current-effective-time)))
;; ——— Macros ——————————————————————————————————————————————————————————————————
(defmacro worf-dotimes-protect (n &rest bodyform)
"Execute N times the BODYFORM unless an error is signaled.
Return nil couldn't execute BODYFORM at least once.
Otherwise return t."
(declare (indent 1))
`(let ((i 0)
out)
(ignore-errors
(while (<= (cl-incf i) ,n)
,@bodyform
(setq out t)))
out))
(defmacro worf-flet (binding &rest body)
"Temporarily override BINDING and execute BODY."
(declare (indent 1))
(let* ((name (car binding))
(old (cl-gensym (symbol-name name))))
`(let ((,old (symbol-function ',name)))
(unwind-protect
(progn
(fset ',name (lambda ,@(cdr binding)))
,@body)
(fset ',name ,old)))))
;; ——— Key binding machinery ———————————————————————————————————————————————————
(defun worf--insert-or-call (def alist)
"Return a lambda to call DEF if position is special.
Otherwise call `self-insert-command'."
(let ((disable (cdr (assoc :disable alist)))
(break (cdr (assoc :break alist))))
`(lambda ,(help-function-arglist def)
,(format "Call `%s' when special, self-insert otherwise.\n\n%s"
(symbol-name def) (documentation def))
,(interactive-form def)
(let (cmd)
(cond ((worf--special-p)
,(when disable `(,disable -1))
(,def ,@(delq '&rest (delq '&optional (help-function-arglist def))))
(unless (or ,break (worf--special-p))
(worf-up 1)))
(t
(setq this-command 'org-self-insert-command)
(org-self-insert-command 1)))))))
(defvar ac-trigger-commands '(self-insert-command))
(defvar company-begin-commands '(self-insert-command))
(defun worf--flag-to-alist (lst flag)
"If FLAG is on LST, change it to (FLAG . t)."
(let ((x (memq flag lst)))
(when x
(setcar x (cons flag t)))
lst))
(defun worf-define-key (keymap key def &rest plist)
"Forward to (`define-key' KEYMAP KEY DEF)
DEF is modified by `worf--insert-or-call'."
(let ((func (defalias (intern (concat "wspecial-" (symbol-name def)))
(worf--insert-or-call def (worf--flag-to-alist
plist :break)))))
(unless (member func ac-trigger-commands)
(push func ac-trigger-commands))
(unless (member func company-begin-commands)
(push func company-begin-commands))
(unless (memq func flyspell-delayed-commands)
(add-to-list 'flyspell-delayed-commands func))
(define-key keymap (kbd key) func)))
;; ——— Verb machinery ——————————————————————————————————————————————————————————
(defvar worf-known-verbs '(worf-keyword-mode)
"List of registered verbs.")
(defun worf-disable-verbs-except (verb)
"Disable all verbs except VERB."
(mapc
(lambda (v) (funcall v -1))
(remq verb worf-known-verbs)))
(defmacro worf-defverb (name grammar)
(let ((sym (intern (format "worf-%s-mode" name)))
(keymap (intern (format "worf-%s-mode-map" name)))
(doc (format "%s verb." (capitalize name)))
(lighter (format " [%s]" name)))
`(progn
(defvar ,keymap (make-sparse-keymap))
(define-minor-mode ,sym
,doc
:keymap ,keymap
:group 'worf
:lighter ,lighter
(cond (,sym
(worf-disable-verbs-except ',sym))
(t nil)))
(mapc (lambda (x)
(let ((y (memq :disable x)))
(when y
(setcar y (cons :disable ',sym))))
(apply 'worf-define-key (cons ,keymap x)))
,grammar)
(unless (memq ',sym worf-known-verbs)
(push ',sym worf-known-verbs))
worf-known-verbs)))
;; ——— Verbs: change ———————————————————————————————————————————————————————————
(defun worf-change-name ()
"Change #+name of the current source block."
(interactive)
(let ((el (org-element-at-point)))
(if (eq (org-element-type el) 'src-block)
(let ((beg (org-element-property :begin el)))
(if (org-element-property :name el)
(let ((end (org-element-property :end el))
(case-fold-search t))
(goto-char beg)
(re-search-forward "#\\+name: " end)
(delete-region (point)
(line-end-position)))
(goto-char beg)
(insert "#+name: \n")
(backward-char)))
(error "Not in a source block"))))
(defun worf-mark ()
"Mark the title of current heading."
(interactive)
(cond ((region-active-p)
(deactivate-mark)
(worf-backward))
((worf--special-p)
(org-back-to-heading)
(re-search-forward " ")
(set-mark (point))
(end-of-line))
(t
(setq this-command 'org-self-insert-command)
(org-self-insert-command 1))))
(worf-defverb
"change"
'(("j" org-metadown)
("k" org-metaup)
("h" org-metaleft)
("l" org-metaright)
("t" org-set-tags-command :disable)
("n" worf-change-name :disable :break)
("a" org-meta-return :disable :break)))
(defhydra hydra-worf-change (:idle 1.0
:hint nil)
"
^ ^ _w_ ^ ^ _t_ags _p_rop _r_: shiftcontrol
_h_ ^+^ _l_ _n_ame _e_dit _i_: shift
^ ^ _s_ ^ ^ _a_dd _T_ime _f_: shiftmeta (tree)"
;; arrows
("j" worf-down :exit t)
("k" worf-up :exit t)
("w" org-metaup)
("s" org-metadown)
("h" org-metaleft)
("l" org-metaright)
("e" move-end-of-line :exit t)
;; modes
("f" worf-change-tree-mode :exit t)
("i" worf-change-shift-mode :exit t)
("r" worf-change-shiftcontrol-mode :exit t)
;; misc
("p" org-set-property :exit t)
("t" org-set-tags-command :exit t)
("T" worf-change-time :exit t)
("n" worf-change-name :exit t)
("a" org-meta-return :exit t)
("o" hydra-worf-keyword/body :exit t)
("m" worf-archive-and-commit :exit t)
("q" nil)
("c" nil))
(defvar-local worf--current-effective-time nil)
(defun worf--current-effective-time (orig-fn)
(or worf--current-effective-time
(funcall orig-fn)))
(defun worf-change-time ()
"Set `current-time' in the current buffer for `org-todo' timestamps.
Use `keyboard-quit' to unset it."
(interactive)
(setq worf--current-effective-time
(condition-case nil
(org-read-date t 'totime)
(quit nil))))
(defhydra hydra-worf-f (:idle 1.0
:exit t)
("f" (setq prefix-arg 9999) "fast-forward")
("s" worf-schedule-today "schedule today")
("d" org-schedule "delay"))
(defun worf-schedule-today (arg)
(interactive "p")
(org-schedule nil (format "%+d" (- arg 1))))
;; ——— Verbs: change tree ——————————————————————————————————————————————————————
(worf-defverb
"change-tree"
'(("j" org-shiftmetadown)
("k" org-shiftmetaup)
("h" org-shiftmetaleft)
("l" org-shiftmetaright)))
;; ——— Verbs: change shift —————————————————————————————————————————————————————
(worf-defverb
"change-shift"
'(("j" org-shiftdown)
("k" org-shiftup)
("h" org-shiftleft)
("l" org-shiftright)))
;; ——— Verbs: change shift control —————————————————————————————————————————————
(worf-defverb
"change-shiftcontrol"
'(("j" org-shiftcontroldown)
("k" org-shiftcontrolup)
("h" org-shiftcontrolleft)
("l" org-shiftcontrolright)))
;; ——— Verbs: clock ————————————————————————————————————————————————————————————
(worf-defverb
"clock"
'(("i" org-clock-in :disable)
("o" org-clock-out :disable)))
(defun worf-clock-in-from-end (end)
"Clock into the current heading from BEG to END.
END is a time. BEG is END minus the amount of minutes entered."
(let* ((diff (seconds-to-time
(* 60 (string-to-number
(read-string "Minutes spent: ")))))
(start-time (time-subtract end diff)))
(org-clock-in nil start-time)
(org-clock-out nil nil end)))
(defun worf-log-time (start-time end-time)
"Insert clocking info from START-TIME to END-TIME into the current logbook."
(save-excursion
(org-back-to-heading)
(goto-char (org-log-beginning))
(if (looking-at ":LOGBOOK:")
(beginning-of-line 2)
(insert ":LOGBOOK:\n:END:\n")
(beginning-of-line 0))
(insert "CLOCK: ")
(org-insert-time-stamp start-time 'with-hm 'inactive)
(insert "--")
(org-insert-time-stamp end-time 'with-hm 'inactive)
(let* ((seconds (time-subtract end-time start-time))
(hours (floor (/ seconds 3600)))
(minutes (/ (- seconds (* 3600 hours)) 60)))
(insert (format " => %d:%02d\n" hours minutes)))))
(defun worf-clock-in-and-out (arg)
"Clock-in and out of a missed deadline.
The clock-in time is always the deadline's original time.
The clock-out time is the clock in time plus user-specified
number of minutes.
When ARG is 2, mark the deadline as DONE at the clock-out time.
When ARG is 3, the clock end time becomes the current time.
Works both in a buffer and in the agenda."
(interactive "p")
(save-window-excursion
(when (eq major-mode 'org-agenda-mode)
(let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
(org-agenda-error))))
(switch-to-buffer (marker-buffer hdmarker))
(goto-char hdmarker)))
(org-back-to-heading)
(if (= arg 3)
(worf-clock-in-from-end (current-time))
(let* ((heading (org-element-at-point))
(deadline (or (org-element-property :deadline heading)
(org-element-property :scheduled heading))))
(if (null deadline)
(if (setq deadline (org-element-property :closed heading))
(worf-clock-in-from-end
(org-timestamp-to-time deadline))
(worf-clock-in-from-end (current-time)))
(let* ((timestamp (org-element-property :raw-value deadline))
(parsed-timestamp (org-parse-time-string timestamp t))
(start-time (if (null (and (nth 1 parsed-timestamp)
(nth 2 parsed-timestamp)))
(apply #'encode-time (org-parse-time-string (org-read-date)))
(apply #'encode-time parsed-timestamp)))
(time-str (read-string "Minutes spent: "))
(diff (if (string= time-str "")
(time-subtract (current-time) start-time)
(seconds-to-time
(* 60 (string-to-number time-str)))))
(end-time (time-add start-time diff)))
(worf-log-time start-time end-time)
(org-add-planning-info 'closed end-time)))
(when (eq arg 2)
(let ((org-log-done nil))
(org-todo 'done))
(save-buffer)))))
(when (eq major-mode 'org-agenda-mode)
;; `org-agenda-list' uses `current-prefix-arg', why...
(setq current-prefix-arg nil)
(org-agenda-redo t)))
;; ——— Verbs: delete ———————————————————————————————————————————————————————————
(defun worf-delete-k (arg)
(interactive "p")
(let ((pt (point)))
(when (ignore-errors
(org-speed-move-safe
'outline-previous-visible-heading) t)
(kill-region pt (point)))))
(defun worf-delete-w ()
"Delete keyword from current heading."
(interactive)
(org-todo 'none)
(org-back-to-heading))
(defun worf-delete-name ()
"Delete #name of the current source block."
(interactive)
(let ((el (org-element-at-point)))
(if (eq (org-element-type el) 'src-block)
(let ((beg (org-element-property :begin el)))
(if (org-element-property :name el)
(let ((end (org-element-property :end el))
(case-fold-search t))
(goto-char beg)
(re-search-forward "#\\+name: " end)
(delete-region (line-beginning-position)
(1+ (line-end-position))))
(error "Source block already doesn't have a name")))
(error "Not in a source block"))))
(defun worf-cut-subtree (arg)
(interactive "p")
(let (beg end)
(org-back-to-heading t)
(setq beg (point))
(save-match-data
(save-excursion
(outline-end-of-heading))
(ignore-errors
(org-forward-heading-same-level
(1- arg)
t))
(org-end-of-subtree t t))
(setq end (min (point) (- (point-max) 2)))
(skip-chars-backward "\n ")
(delete-region (point) end)
(setq end (point))
(kill-region beg end)
(backward-char 1)
(org-back-to-heading t)
(message
"Cut: Subtree(s) with %d characters"
(length (current-kill 0)))))
(worf-defverb
"delete"
'(("p" org-delete-property :disable)
("k" worf-delete-k :disable)
("j" worf-cut-subtree :disable)
("w" worf-delete-w :disable)
("n" worf-delete-name :disable)))
;; ——— Verbs: yank —————————————————————————————————————————————————————————————
(worf-defverb
"yank"
'(("j" org-copy-subtree :disable)))
;; ——— Verbs: mark —————————————————————————————————————————————————————————————
(defun worf-mark-down (arg)
(interactive "p")
(let ((bnd (worf--bounds-subtree)))
(worf-down (- arg 1))
(set-mark (cdr (worf--bounds-subtree)))
(goto-char (car bnd))))
(defun worf-mark-left ()
(interactive)
(worf-left)
(let ((bnd (worf--bounds-subtree)))
(goto-char (car bnd))
(set-mark (cdr bnd))))
(worf-defverb
"mark"
'(("j" worf-mark-down :disable)
("h" worf-mark-left :disable)))
;; ——— Verbs: keyword ——————————————————————————————————————————————————————————
(defvar worf-keyword-mode-map
(make-sparse-keymap))
(defvar worf-keyword-mode-lighter "")
(defvar worf--keyword nil
"Current `org-mode' keyword, i.e. one of \"TODO\", \"DONE\" etc.")
(defsubst worf-mod-keyword ()
"Return current keyword."
worf--keyword)
(define-minor-mode worf-keyword-mode
"Minor mode that makes j/k to move by keywords."
:keymap worf-keyword-mode-map
:group 'worf
:lighter worf-keyword-mode-lighter
(cond (worf-keyword-mode
(call-interactively 'worf-keyword)
(add-hook 'post-command-hook 'worf--invalidate-keyword))
(t
(setq worf--keyword nil))))
(defun worf-keyword (&optional keyword)
"Set the current keyword.
All next `worf-down' and `worf-up' will move by this keyword.
When the chain is broken, the keyword is unset."
(interactive)
(setq worf--keyword
(or keyword
(let* ((c (read-char "[t]odo, [d]one, [n]ext, [c]ancelled")))
(message
(cl-case c
(?t "TODO")
(?d "DONE")
(?n "NEXT")
(?c "CANCELLED")))))))
(defhydra hydra-worf-keyword (:idle 1.5 :color teal)
("t" (org-todo "TODO") "TODO")
("d" (org-todo "DONE") "DONE")
("n" (org-todo "NEXT") "NEXT")
("c" (org-todo "CANCELLED") "CANCELLED"))
(defvar worf--keyword-no-invalidate-list
'(wspecial-worf-keyword-mode
worf-keyword
wspecial-worf-up
wspecial-worf-down
wspecial-digit-argument))
(defun worf--invalidate-keyword ()
(message "%s" this-command)
(unless (memq this-command worf--keyword-no-invalidate-list)
(worf-keyword-mode -1)
(remove-hook 'post-command-hook 'worf--invalidate-keyword)))
(let ((map worf-keyword-mode-map))
(worf-define-key map "w" 'worf-keyword))
(defun worf--set-change-switches (key mode)
"Bind MODE to KEY for change modes."
(mapc (lambda (map) (worf-define-key map key mode))
(list worf-change-mode-map
worf-change-tree-mode-map
worf-change-shift-mode-map
worf-change-shiftcontrol-mode-map)))
(worf--set-change-switches "c" 'worf-change-mode)
(worf--set-change-switches "f" 'worf-change-tree-mode)
(worf--set-change-switches "s" 'worf-change-shift-mode)
(worf--set-change-switches "r" 'worf-change-shiftcontrol-mode)
;; ——— Nouns: arrows ———————————————————————————————————————————————————————————
(defvar worf-recenter nil)
(defun worf-recenter-mode ()
"Toggle centering on the current window line.
`worf-down' and `worf-up' are affected by this, and will
automatically recenter."
(interactive)
(if worf-recenter
(progn
(hl-line-mode -1)
(setq worf-recenter nil))
(hl-line-mode 1)
(setq worf-recenter (- (line-number-at-pos)
(line-number-at-pos (window-start))))))
(defun worf-up (arg)
"Move ARG headings up."
(interactive "p")
(cond ((worf-mod-keyword)
(worf-dotimes-protect arg
(worf--prev-keyword (worf-mod-keyword))))
((worf--at-property-p)
(worf--prev-property arg))
((looking-at worf-sharp)
(worf--sharp-up))
(t
(zo-up arg)
(when worf-recenter
(recenter worf-recenter)))))
(defun worf-down (arg)
"Move ARG headings down."
(interactive "p")
(cond ((worf-mod-keyword)
(worf-dotimes-protect arg
(worf--next-keyword (worf-mod-keyword))))
((worf--at-property-p)
(worf--next-property arg))
((looking-at worf-sharp)
(if (save-excursion
(re-search-backward (concat "^\\(?:" outline-regexp "\\)") nil t))
(worf-dotimes-protect arg
(worf--sharp-down))
(org-next-visible-heading arg)))
(t
(let ((actual (zo-down arg)))
(when (and (numberp actual) (< actual arg))
(message "Reached end after %d headings" actual)))
(when worf-recenter
(recenter worf-recenter)))))
(defun worf-right ()
"Move right."
(interactive)
(let ((pt (point))
result)
(save-restriction
(org-narrow-to-subtree)
(forward-char)
(if (re-search-forward worf-regex nil t)
(progn
(goto-char (match-beginning 0))
(setq result t))
(goto-char pt)))
(worf--ensure-visible)
result))
(defun worf-left ()
"Move one level up backwards."
(interactive)
(if (looking-at worf-sharp)
(goto-char (car (worf--bounds-subtree)))
(ignore-errors
(org-up-heading-safe))))
;; ——— Nouns: property —————————————————————————————————————————————————————————
(defun worf-property ()
"Operate on property."
(interactive)
(cl-destructuring-bind (beg . end)
(worf--bounds-subtree)
(let ((pt (car (org-get-property-block beg))))
(if pt
(progn
(unless (bound-and-true-p reveal-mode)
(goto-char beg)
(org-show-subtree))
(goto-char pt))
(error "No properties. Use \"c p\" to add properties")))))
(defun worf-paste ()
(interactive)
(let ((bnd (worf--bounds-subtree)))
(when bnd
(goto-char (cdr bnd))
(skip-chars-backward "\n")
(forward-char 1)
(save-excursion (yank)))))
(defun worf-occur ()
(interactive)
(let* ((bnd (worf--bounds-subtree))
(candidates
(save-restriction
(narrow-to-region (car bnd) (cdr bnd))
(swiper--init)
(swiper--candidates))))
(ivy-read "pattern: " candidates
:require-match t
:update-fn #'swiper--update-input-ivy
:action #'swiper--action
:unwind #'swiper--cleanup
:caller 'worf-occur)))
;; ——— Nouns: new heading ——————————————————————————————————————————————————————
(require 'reveal)
(defun worf-add (arg)
"Add a new heading below.
Positive ARG shifts the heading right.
Negative ARG shifts the heading left."
(interactive "p")
(let ((lvl (org-current-level))
(spacing (max (abs
(save-excursion
(skip-chars-backward "\n")))
1)))
(if (zo-down-visible)
(progn
(backward-char)
(skip-chars-backward "\n")
(insert "\n")
(worf--ensure-visible))
(outline-end-of-subtree)
(skip-chars-backward "\n")
(dotimes (i spacing)
(insert "\n"))
(reveal-post-command))
(insert (concat (make-string lvl ?*) " "))
(cond ((> arg 1)
(worf-dotimes-protect (1- arg)
(org-metaright)))
((cl-minusp arg)
(worf-dotimes-protect (- arg)
(org-metaleft))))
(when worf-keyword-mode
(insert (worf-mod-keyword) " ")
(worf-keyword-mode -1))))
(defun worf-new-right (arg)
(interactive "p")
(org-insert-heading-respect-content)
(worf-dotimes-protect arg
(org-metaright)))
(defun worf-new-down ()
(interactive)
(end-of-line)
(org-insert-heading-respect-content)
(beginning-of-line))
(defhydra worf-new (:exit t)
("j" worf-new-down)
("k" org-insert-heading)
("h" org-metaleft)
("l" worf-new-right))
(defun worf-new-copy ()
"Copy marked region to kill ring."
(interactive)
(if (region-active-p)
(kill-new
(buffer-substring-no-properties
(region-beginning)
(region-end)))))
;; ——— Other movement ——————————————————————————————————————————————————————————
(defun worf-backward ()
"Go backwards to closest special position."
(interactive)
(when (re-search-backward worf-regex-full nil t)
(while (or (worf--invisible-p)
(not (looking-at "[*#]"))
(not (bolp)))
(worf-backward))))
(defun worf-forward ()
"Go forwards to closest special position."
(interactive)
(forward-char 1)
(re-search-forward worf-regex-full nil t)
(beginning-of-line))
(defun worf-back-to-heading ()
(interactive)
(org-back-to-heading))
(defvar worf-beginning-of-line t)
(defun worf-beginning-of-line ()
"Replaces `org-beginning-of-line'."
(interactive)
(beginning-of-line))
(defcustom worf-completion-method 'ivy
"Method to select a candidate from a list of strings."
:type '(choice
(const :tag "Ivy" ivy)
;; sensible choice for many tags
(const :tag "Helm" helm)))
(defun worf--goto-candidates ()
(let ((extra (< (buffer-size) 100000))
candidates)
(org-map-entries
(lambda ()
(let ((comp (org-heading-components))
(h (org-get-heading)))
(push
(cons (format "%d%s%s" (car comp)
(make-string (1+ (* 2 (1- (car comp)))) ?\ )
(if (get-text-property 0 'fontified h)
h
(worf--pretty-heading (nth 4 comp) (car comp))))
(point))
candidates)
(when extra
(save-restriction
(narrow-to-region
(progn (org-back-to-heading t) (point))
(progn (worf-down 1) (point)))
(save-excursion
(goto-char (point-min))
(while (re-search-forward "^#\\+name \\(.*\\)$" nil t)
(push (cons (propertize (match-string 1) 'face 'org-meta-line)
(line-beginning-position))
candidates))))))))
(nreverse candidates)))
(defun worf-goto-action (x)
(with-ivy-window
(goto-char (cdr x))
(outline-show-children 1000)
(worf-more)))
(declare-function helm "ext:helm")
(defun worf-goto ()
"Jump to a heading with completion."
(interactive)
(let ((cands (worf--goto-candidates)))
(cond ((eq worf-completion-method 'helm)
(require 'helm-multi-match)
(let (helm-update-blacklist-regexps
helm-candidate-number-limit)
(helm :sources
`((name . "Headings")
(candidates . ,cands)
(action . worf-goto-action)
(pattern-transformer . worf--pattern-transformer)))))
((eq worf-completion-method 'ivy)
(ivy-read "Heading: " cands
:action 'worf-goto-action)))))
(defun worf-meta-newline ()
"Copy current markup block at newline.
Sometimes useful for #+LaTeX_HEADER."
(interactive)
(if (looking-back "^#\\+\\([^:]*:\\).*"
(line-beginning-position))
(progn
(end-of-line)
(insert "\n#+" (match-string 1) " "))
(indent-new-comment-line)))
;; ——— View ————————————————————————————————————————————————————————————————————
(defun worf-tab (arg)
"Hide/show heading.
When ARG is 0, show the heading contents, no matter if the
heading fold state.
When ARG is 1, toggle between fully hidden state and a fully
visible state.
When ARG isn't 0 or 1, show full file contents for that level,
i.e. `org-shifttab'.
When at a #+ marker, forward to `org-cycle'."
(interactive "p")
(let ((v (this-command-keys-vector))
(bnd (zo-bnd-subtree)))
(when (let ((case-fold-search t))
(looking-at "#\\+end"))
(worf--sharp-up))
(cond ((eq (car (org-element-at-point)) 'clock)
(org-clock-update-time-maybe))
((looking-at "#\\+DOWNLOADED:")
(let ((end (save-excursion (search-forward "]]" (cdr bnd)))))
(if (eq (get-char-property (1- end) 'invisible) 'outline)
(outline-flag-region (line-end-position) end nil)
(outline-flag-region (line-end-position) end t))))
((looking-at "#\\+")
(org-cycle))
((looking-at "^:")
(org-cycle))
((= arg 0)
(outline-flag-region (car bnd) (cdr bnd) t)
(org-cycle-internal-local)
(when (eq (char-before (cdr bnd)) 10)
(outline-flag-region (- (cdr bnd) 1) (cdr bnd) nil)))
((and (= 2 (length v))
(string-match "[0-9]" (concat v)))
(org-shifttab arg))
(t
(let ((eoh (car bnd))
(eos (cdr bnd)))
(if (and (memq (get-char-property (1- eos) 'invisible) '(outline org-hide-drawer))
(eq (get-char-property (1+ eoh) 'invisible) 'outline))
(outline-flag-region eoh eos nil)
(outline-flag-region eoh eos t)))))))
(defun worf-tab-contents ()
"Show only the names of the heading's children."
(interactive)
(let ((bnd (zo-bnd-subtree)))
(if (and (get-char-property (line-end-position 2) 'invisible)
(not (get-char-property (line-beginning-position 2) 'invisible)))
(outline-flag-region (car bnd) (cdr bnd) nil)
(zo-fold-heading 'current))))
(defhydra hydra-org-tab (:color blue
:hint nil)
"
_g_lobal cycle _b_ranches
_a_ll _c_hildren
_s_tartup
"
("s" (org-global-cycle '(4)))
("g" org-global-cycle :exit nil)
("a" outline-show-all)
("b" outline-show-branches)
("c" outline-show-children))