-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathorgqda.el
2145 lines (1925 loc) · 87.1 KB
/
orgqda.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
;;; orgqda.el --- Qualitative data analysis using org-mode -*- lexical-binding: t -*-
;; Copyright (C) 2014-2022 Anders Johansson
;; Author: Anders Johansson <[email protected]>
;; Version: 0.5
;; Created: 2014-10-12
;; Modified: 2024-10-14
;; Package-Requires: ((emacs "25.1") (org "9.3") (hierarchy "0.6.0"))
;; Keywords: outlines, wp
;; URL: https://www.gitlab.com/andersjohansson/orgqda
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation; either version 2, or (at
;; your option) any later version.
;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; orgqda defines a minor mode and several commands for making coding
;; and collection of coded snippets possible in text written in
;; org-mode. It works in a simple (and perhaps stupid) way by viewing
;; org-mode tags added to degenerate inlinetasks as applying to the
;; preceding paragraph.
;;; Code:
(require 'bookmark)
(require 'org)
(require 'org-inlinetask)
(require 'org-element)
(require 'org-agenda)
(require 'cl-lib)
(require 'subr-x) ;if-let, thread-last
(require 'hierarchy)
;;;; Variables
(defgroup orgqda nil
"Customizations for ‘orgqda-mode’."
:group 'org)
;;;###autoload
(defcustom orgqda-csv-dir "~"
"Directory for saving csv-files."
:type 'directory
:safe 'file-directory-p)
(defcustom orgqda-collect-coverage nil
"Display coverage (percentage of file the coded segment makes up) in ‘orgqda’."
:type 'boolean)
(defcustom orgqda-tag-collect-extra-info nil
"Possibly adds extra info to extracted tagged parts.
An alist where keys are regexps to be matched against ‘buffer-name’
and values are Lisp forms that are evaluated to get extra info.
An example that adds a possible parent heading on level 4 for
buffers with names containing \"fieldnotes\":
\((\"fieldnotes\" . (format \" (from: %s)\" (orgqda-get-parent-hl 4))))"
:type '(alist :key-type regexp :value-type sexp))
(defcustom orgqda-transform-collected-paragraph-function #'identity
"Function for transforming or wrapping extracted paragraphs when collecting.
A function receving the paragraph as a string, should return a
string. Could be useful if you for example want extracts to be
wrapped in org quote blocks. Only applies to extracted
paragraphs (not subtrees or inlinetasks with END.)"
:type 'function)
(defcustom orgqda-collect-from-all-files t
"Non-nil to work across files in variable ‘orgqda-tag-files’.
This applies to the tag listing and collection commands in orgqda."
:type 'boolean)
(defcustom orgqda-respect-restriction-for-single-file t
"If only collecting tags from a single file, collect in narrowed buffer."
:type 'boolean
:safe #'booleanp)
(defcustom orgqda-tag-collect-extra-info-csv nil
"Like ‘orgqda-tag-collect-extra-info’ for the first extra-field in csv-export."
:type '(alist :key-type regexp :value-type sexp))
(defcustom orgqda-tag-collect-extra-info2-csv nil
"Like ‘orgqda-tag-collect-extra-info’ for the second extra-field in csv-export."
:type '(alist :key-type regexp :value-type sexp))
(defcustom orgqda-convert-csv-to-encoding nil
"Encoding to use for saved csv files.
By default csv files are saved with the encoding used by Emacs or
the files. Setting this to a symbol that represents another
encoding will ensure all characters are of this encoding and
replace those that are not by ? in saved csv files. t is a
shortcut for \"iso-8859-1\""
:type (append
'(choice
(const nil :tag "don’t convert")
(const t :tag "iso-8859-1"))
(cl-loop for cs in coding-system-list
collect (list 'const cs))))
(defcustom orgqda-exclude-tags nil
"Tags to exclude when listing coding tags.
Applies to ‘orgqda-list-tags’ and ‘orgqda-list-tags-full’."
:type '(choice
(const :tag "None" nil)
(repeat :tag "List of tags" string))
:safe #'orgqda--list-of-strings-p)
(defcustom orgqda-hierarchy-delimiter "_"
"The character to use for delimiting a hierarchy within tags.
One of: _@#%, or nil to disable hierarchical grouping."
:type '(choice (const "_")
(const "@")
(const "#")
(const "%")
(const :tag "Disable" nil)))
(defcustom orgqda-exclude-empty-file-trees t
"When non-nil, excludes listing files without matches for current tag."
:type 'boolean)
(defcustom orgqda-sort-parameters
'((count-decreasing
(:description . "By count, decreasing")
(:data-get . orgqda--get-tag-count)
(:buffer-get . orgqda--hl-get-count)
(:alist-get . cdr)
(:completion-get . orgqda-completion--get-count)
(:compare . >))
(a-z
(:description . "A-Z")
(:compare . orgqda--string-lessp)
(:char . ?a))
(z-a
(:description . "Z-A")
(:compare . orgqda--string-greaterp)
(:char . ?A))
(count-increasing
(:description . "By count, increasing")
(:data-get . orgqda--get-tag-count)
(:buffer-get . orgqda--hl-get-count)
(:alist-get . cdr)
(:completion-get . orgqda-completion--get-count)
(:compare . <)))
"Alist of sorting names (symbols) and associated functions.
cdr of each key is plist with functions, used for getting sort keys
and comparing in different contexts.
When just acting on the text of the tag, it is sufficient to give
a :compare function.
When fetching other data (mainly count), functions :data-get (for
the internal data store when populating tag lists), :buffer-get
\(for sorting in listing buffers), :alist-get (for
‘orgqda--get-tags-alist’), and :completion-get (for orgqda-completion.el)
are needed."
:type '(repeat
(list
(symbol :tag "Name")
(set :inline t
(cons :tag "Description, mandatory"
(const :format "" :description) string)
(cons :tag "Function for comparing two values, mandatory"
(const :format "" :compare) function)
(cons :tag "Character matching a sort character for ‘org-sort-entries’."
(const :char) character)
(cons :tag "Function for fetching value in data."
(const :format "" :data-get) function)
(cons :tag "Function for fetching value in buffer."
(const :format "" :buffer-get) function)
(cons :tag "Function for fetching value in alist."
(const :format "" :alist-get) function)
(cons :tag "Function for fetching value in completion list."
(const :format "" :completion-get) function)))))
(defun orgqda--sort-parameter-get (key parameter &optional default)
"Get sort PARAMETER for KEY or nil or DEFAULT if not found.
See ‘orgqda-sort-parameters’."
(if-let ((a (alist-get key orgqda-sort-parameters))
(p (alist-get parameter a)))
p
default))
(defun orgqda--read-sort-choice ()
"Completing read for sorting options from ‘orgqda-sort-parameters’."
(intern-soft (completing-read "Sort by: " (mapcar #'car orgqda-sort-parameters) nil t)))
(defcustom orgqda-keep-tags-sorted nil
"If non-nil, keep the taglist in the entry sorted in ‘orgqda-mode’.
If non-nil, should be a sorting scheme from
‘orgqda-sort-parameters’, or optionally a comparison function.
You could directly set ‘org-tags-sort-function’, but this is for
using it locally when using ‘orgqda-mode’ and with simple options
corresponding to orgqda sorting.
Most stable and useful is probably to sort alphabetically, using
‘a-z’ or ‘z-a’. Sorting by count means sorting by the current
“popularity” of tags across the orgqda collection and won’t be
updated when tags are changed in other places than this headline."
:type 'symbol
:safe #'symbolp)
(defcustom orgqda-default-sort-order 'count-decreasing
"Default order for sorting when listing tags.
See ‘orgqda-sort-parameters’ for options."
:type 'character
:safe #'characterp)
(defcustom orgqda-only-count-matching nil
"When non-nil, only entries with matching tags are counted and collected.
Each item in this list is a regex matched against tags with
‘string-match-p’.
This is useful for temporarily working on a subset of the project, defined
via a certain tag or tag-prefix."
:type '(repeat string)
:safe #'orgqda--list-of-strings-p)
(defcustom orgqda-use-tag-inheritance nil
"When non-nil, count entries using tag inheritance.
Useful together with ‘orgqda-only-count-matching’, if you for
example want to analyse data for a specific kind of entry (using
a tag) but those entries should be considered tagged with their
parents’ tags."
:type 'boolean
:safe #'booleanp)
(defcustom orgqda-tagcount-show-files nil
"When non-nil, show the counts for individual files when listing tags.
If you for example have a group of interview transcripts in
different files this gives a good overview of which interview
each tag was used in.
One of ‘all’, for displaying it on all nodes in the tag listing,
‘not-parents’ for only showing the overall count for parents in a
hierarchical listing, or nil, for disabling it."
:type '(choice (const :tag "For all" all)
(const :tag "Not parents" not-parents)
(const :tag "Disable" nil))
:safe #'symbolp)
(defcustom orgqda-tagcount-files-transform-functions '(file-name-base orgqda--file-name-remove-parentheses)
"List of functions to apply to displayed file names for tagcounts.
Transforms the file name with each function in list order.
It is important that ‘orgqda--file-name-remove-parentheses’ is in
the list, otherwise updating codebook tag lists will fail."
:type '(repeat function))
(defcustom orgqda-taglink-include-filename t
"Style for taglinks (otag) when listing tags.
Non-nil means include the filename for the file where searching
started. When the filename is included, we can be more sure that
following the link looks in the right project."
:type 'boolean
:safe #'booleanp)
(defcustom orgqda-tag-action 'collect
"Action to invoke on click or \[org-open-at-point] on a tag in a headline.
Nil gives org mode default, which is to invoke ‘org-tags-view’
but the orgqda functions are probably more useful. ‘collect’
collects tags and ‘codebook’ looks up the tag in
‘orgqda-codebook-file’."
:type '(choice (const :tag "Collect all coded instances" collect)
(const :tag "Lookup tag in codebook file" codebook)
(const :tag "Fallback to standard org behaviour" nil))
:safe #'symbolp)
(defun orgqda--file-name-remove-parentheses (filename)
"Return FILENAME with parentheses removed."
(string-replace
")" ""
(string-replace "(" "" filename)))
;;;###autoload
(defvar-local orgqda-tag-files nil
"Extra files from which tags should be fetched for completion.
A list of files and directories, or the name of a file
containing such a list. Relative paths in such a file are read as
relative to the file itself.
For directories, all .org-files (matched by
‘org-agenda-file-regexp’) are added.
Usually set by the user as a file or dir local variable.")
;;;###autoload
(put 'orgqda-tag-files 'safe-local-variable
#'orgqda--string-or-list-of-strings-p)
;;;###autoload
(defvar-local orgqda-codebook-file nil
"A file that is used as a codebook.
Including lists of tags (otag-links) This file will be updated
when tags are renamed.
Usually set by the user as a file or dir local variable.")
;;;###autoload
(put 'orgqda-codebook-file 'safe-local-variable
#'orgqda--string-or-nil-p)
;;;###autoload
(defun orgqda--string-or-list-of-strings-p (arg)
"Return t if ARG is a string or a list of strings."
(or (orgqda--string-or-nil-p arg)
(orgqda--list-of-strings-p arg)))
;;;###autoload
(defun orgqda--list-of-strings-p (arg)
"Return t if ARG is a list of strings."
(and (listp arg) (cl-every #'orgqda--string-or-nil-p arg)))
(defun orgqda--string-or-nil-p (arg)
"Return t if ARG is a string or nil."
(or (stringp arg) (null arg)))
(defvar-local orgqda--originating-buffer nil
"Buffer from which the current orgqda list or collection was invoked.")
(defvar-local orgqda--taglist-parameters nil
"Parameters used to generate taglist in current buffer.")
(defvar-local orgqda--old-org-current-tag-alist nil
"Saved state of ‘org-current-tag-alist’ before enabling ‘orgqda-mode’.")
(defvar-local orgqda--current-search nil
"The tag search string for current ‘orgqda-view-mode’ buffer.")
;; from orgqda-completion.el, to silence byte-compiler
(defvar orgqda-completion-mode)
;;;; Macros and defsubst
(defmacro orgqda--temp-work (widened? &rest body)
"Macro for working on BODY temporarily, possibly in WIDENED buffer.
Shortcut for:
\(‘save-excursion’
(‘save-restriction’
(‘widen’) (‘goto-char’) (‘point-min’)))."
(declare (indent 1) (debug t))
`(save-excursion
(save-restriction
(when ,widened? (widen))
(goto-char (point-min))
,@body)))
(defmacro orgqda--with-current-buffer-if (buffer &rest body)
"Execute BODY in BUFFER if it exists, otherwise just execute BODY.
The value returned is the value of the last form in BODY."
(declare (indent 1) (debug t))
`(if (and ,buffer (buffer-live-p ,buffer))
(with-current-buffer ,buffer ,@body)
,@body))
(defmacro orgqda--inhibit-org-startups (&rest body)
"Execute BODY while inhibiting mode hooks and org-startup.
Inhibits hooks for ‘text-mode’, ‘outline-mode’ and ‘org-mode’"
(declare (debug t))
`(let ((text-mode-hook nil)
(outline-mode-hook nil)
(org-mode-hook nil)
(org-agenda-inhibit-startup t)
(org-inhibit-startup t))
,@body))
(defmacro orgqda--with-many-files (manyfiles &rest body)
"Execute BODY efficiently in each file of MANYFILES."
(declare (indent 1))
`(orgqda--inhibit-org-startups
;; this basically copies the essentials for running on a set of
;; files from ‘org-map-entries’
(let ((org-agenda-skip-archived-trees t)
(org-agenda-skip-comment-trees t)
org-todo-keywords-for-agenda
org-done-keywords-for-agenda
org-todo-keyword-alist-for-agenda
org-tag-alist-for-agenda)
(org-agenda-prepare-buffers ,manyfiles)
(dolist (file ,manyfiles)
(with-current-buffer (org-find-base-buffer-visiting file)
,@body)))))
(defsubst orgqda--string-or-empty (string &optional prefix suffix)
"Return STRING with PREFIX and SUFFIX iff STRING is a non-blank string.
Else return empty string."
(cond ((and (stringp string)
(string-match-p "[^[:blank:]]" string))
(concat prefix string suffix))
(t "")))
;;;; Minor mode definitions
;;;###autoload
(define-minor-mode orgqda-mode
"Minor mode for qualitative coding of text material.
Enables tag completion with tags from all files defined in
variable ‘orgqda-tag-files’ (if ‘orgqda-collect-from-all-files’ is non-nil).
Relevant commands not bound to any keys are: ‘orgqda-list-tags’,
‘orgqda-list-tags-full’ and ‘orgqda-collect-tagged’, but see also
‘orgqda-transient’ in library orgqda-transient.el for convenient access to
these functions.
CSV files can be exported as well with
‘orgqda-collect-tagged-csv’, ‘orgqda-collect-tagged-csv-save’,
and ‘orgqda-collect-tagged-csv-save-all’. Be sure to customize
‘orgqda-csv-dir’ first.
\\{orgqda-mode-map}"
:lighter " QDA"
:keymap `((,(kbd "C-c C-x m") . orgqda-insert-inlinetask)
(,(kbd "C-c C-x n") . orgqda-insert-inlinetask-coding))
:group 'orgqda
(if orgqda-mode
(progn
(when orgqda-tag-files
(setq-local org-complete-tags-always-offer-all-agenda-tags t))
(setq orgqda--old-org-current-tag-alist org-current-tag-alist
org-current-tag-alist nil)
(setq-local org-open-at-point-functions
(append '(orgqda-tag-action-at-point)
org-open-at-point-functions))
(setq-local org-tags-sort-function
(or (when (functionp orgqda-keep-tags-sorted) orgqda-keep-tags-sorted)
(orgqda--sort-parameter-get orgqda-keep-tags-sorted :compare)
org-tags-sort-function)))
(kill-local-variable 'org-complete-tags-always-offer-all-agenda-tags)
(kill-local-variable 'org-open-at-point-functions)
(kill-local-variable 'org-tags-sort-function)
(setq org-current-tag-alist orgqda--old-org-current-tag-alist)))
;;;###autoload
(define-minor-mode orgqda-list-mode
"Mode for displaying lists of tags in orgqda.
\\{orgqda-list-mode-map}"
:keymap `((,(kbd "<drag-mouse-1>") . orgqda-drag-merge-tags)
(,(kbd "R") . orgqda-rename-tag)
(,(kbd "P") . orgqda-prefix-tag)
(,(kbd "s") . orgqda-sort-taglist)
(,(kbd "S") . orgqda-sort-taglist-buffer)
(,(kbd "g") . orgqda-revert-taglist)
(,(kbd "q") . quit-window))
:lighter " QDAl")
(define-minor-mode orgqda-codebook-mode
"Minor mode for updating and sorting lists of tags in a codebook file.
\\{orgqda-codebook-mode-map}"
:keymap `((,(kbd "<drag-mouse-1>") . orgqda-drag-merge-tags)
(,(kbd "C-c (") . orgqda-list-mode-map)
([remap org-refile] . orgqda-refile-and-merge-tags))
:lighter "QDAc")
(define-minor-mode orgqda-view-mode
"Minor mode for viewing collected extracts from ‘orgqda-collect-tagged’.
\\{orgqda-view-mode-map}"
:keymap `((,(kbd "g") . orgqda-revert-collected-tags)
([remap org-set-tags-command] . orgqda-tag-in-collection-buffer))
:lighter "QDAv")
;;;; Interactive commands
;;;;; Commands for inserting
(autoload 'org-inlinetask-in-task-p "org-inlinetask")
(declare-function orgqda-helm-tags-set-tags "orgqda-helm-tags")
;;;###autoload
(defun orgqda-insert-inlinetask (&optional after-line title coding)
"Insert a degenerate inlinetask after current paragraph.
With prefix arg AFTER-LINE, after current line.
TITLE is a string defining a title for the inlinetask and CODING
if non-nil additionally calls `org-set-tags-command`."
(interactive "P")
(let ((cg (prepare-change-group))
(oldpoint (point))
(inhibit-read-only t))
(unwind-protect
(progn
(activate-change-group cg)
(unless (org-inlinetask-in-task-p) ; add nothing if already in task
(unless (and (bolp) (eolp)) ; only move if inside a line of text
(if after-line (forward-line) (forward-paragraph)))
(unless (org-inlinetask-in-task-p) ; create inlinetask if not present
(unless (and (bolp) (eolp)) (newline)) ;newline at e.g. eof
(unless (and after-line (bolp) (eolp)) (open-line 1)) ; open-line if at newline
(insert (concat (make-string
(1+ org-inlinetask-min-level) 42)
" " title))))
(when (and coding (org-inlinetask-in-task-p))
(if (bound-and-true-p orgqda-helm-tags-mode)
(orgqda-helm-tags-set-tags)
(org-set-tags-command))))
;; If no tags were actually added, undo.
(if (and coding
(save-excursion
(beginning-of-line)
(and
(looking-at org-complex-heading-regexp)
(not (match-string 5)))))
(progn
(cancel-change-group cg)
(goto-char oldpoint))
(accept-change-group cg)
(move-end-of-line nil)))))
;;;###autoload
(defun orgqda-insert-inlinetask-coding (arg)
"Call ‘orqda-insert-inlinetask’ with coding option and title \"∈\".
Prefix ARG is passed through."
(interactive "P")
(orgqda-insert-inlinetask arg "∈" t))
;;;###autoload
(defun orgqda-code-headline-or-paragraph (after-line)
"Insert tags if on a headline, or insert inlinetask and tags.
Prefix arg AFTER-LINE is passed through to ‘orgqda-insert-inlinetask’.
Suitable for remapping ‘org-set-tags-command’ like this:
\(define-key orgqda-mode-map [remap org-set-tags-command]
#\\='orgqda-code-headline-or-paragraph)."
(interactive "P")
(let ((inhibit-read-only t))
(if (org-at-heading-p)
(org-set-tags-command)
(if (orgqda--codeable-paragraph-p)
(orgqda-insert-inlinetask-coding after-line)
(org-set-tags-command)))))
;;;;; Commands for listing tags
;;;###autoload
(cl-defun orgqda-list-tags (&optional arg &key sort full buffer noupdate roottext startprefix no-tag-files)
"List all tags in this buffer and/or variable ‘orgqda-tag-files’, with counts.
Sorted by count, or alphabetically if optional (prefix) argument
ARG is non-nil.
For non-interactive calls, the rest of the arguments are given as
keywords SORT, as a sort character (see
‘orgqda--create-hierarchical-taglist’). FULL non-nil means also
insert extracted paragraphs for all tags. If a buffer is provided
in BUFFER overwrite this buffer with the list instead of creating
a new. The taglist is normally updated via
‘orgqda--create-hierarchical-taglist’, but this can be prevented
by giving a non-nil NOUPDATE. Then a special list can be used by
setting ‘orgqda--current-htl’ suitably. ROOTTEXT specifies the
text for the root node. STARTPREFIX, searches only tags under
this prefix. NO-TAG-FILES means only collect in current buffer,
ignoring any setting of ‘orgqda-tag-files’."
(interactive "P")
(let* ((origbuffer (current-buffer))
(origfile (buffer-file-name))
(ocm orgqda-only-count-matching)
(include-filename orgqda-taglink-include-filename)
(orgqda-tag-files
(if no-tag-files nil orgqda-tag-files))
;; no need to show origin files if only one, or when
;; displaying full list
(orgqda-tagcount-show-files
(if (and orgqda-tag-files (not full))
orgqda-tagcount-show-files
nil))
tagfiles)
(unless noupdate
(orgqda--create-hierarchical-taglist
(cond
((characterp sort) sort)
(arg 'a-z)
(t orgqda-default-sort-order)))
;; have to fetch the list again here for listing below, it is
;; done deep in the call of
;; ‘orgqda--create-hierarchical-taglist’ above
(setq tagfiles (when orgqda-tag-files orgqda-collect-from-all-files (orgqda-tag-files))))
(if buffer
(progn (pop-to-buffer buffer)
(setq buffer-read-only nil)
(erase-buffer))
(pop-to-buffer
(generate-new-buffer (concat "*orgqda-taglist"
(unless tagfiles
(concat "-" (buffer-name origbuffer)))
"*"))))
(if roottext
(insert (format "* %s\n" roottext))
(insert
(concat "* Orgqda taglist "
(when ocm
(format "(matching: %s) "
(mapconcat #'identity ocm "|")))
(when startprefix
(format "(under prefix ~%s~) " startprefix))
"generated from "
(org-link-make-string
(concat "file:" origfile)
(buffer-name origbuffer))
" at "
(format-time-string "[%Y-%m-%d %a %H:%M]")
"\n"
(when tagfiles
(concat ":ORGQDA_TAG_FILES:\n"
(cl-loop for f in (sort tagfiles #'string-version-lessp)
concat
(concat "- " (org-link-make-string f (file-name-base f)) "\n"))
":END:\n")))))
(orgqda--insert-hierarchical-taglist full origbuffer (if include-filename origfile "") 1 startprefix)
(goto-char (point-min))
(org-mode) (view-mode) (orgqda-list-mode) (flyspell-mode -1)
(orgqda--clone-local-variables origbuffer)
(setq ;; buffer-read-only t
orgqda--originating-buffer origbuffer
orgqda--taglist-parameters
`( :sort ,sort
:full ,full
:startprefix ,startprefix
:roottext ,roottext
:no-tag-files ,no-tag-files))))
;;;###autoload
(defun orgqda-list-tags-full (&optional sort buffer)
"List all tags including extracted parahraphs.
Sorted by count or alphabetically if optional (prefix) argument
SORT is non-nil. Two prefix arguments prompts for a tag prefix to
start from. BUFFER is passed on to ‘orgqda-list-tags’"
(interactive "P")
(orgqda-list-tags
(equal '(4) sort)
:full t
:buffer buffer
:startprefix
(when (equal '(16) sort)
(concat (orgqda--completing-read-prefix
"Prefix to start from: ")
"_"))))
(defun orgqda-revert-taglist ()
"Reverts current ‘orgqda-list-mode’ buffer.
If not in ‘orgqda-list-mode’, calls
‘orgqda-update-taglist-general’."
(interactive)
(if (and orgqda-list-mode orgqda--originating-buffer)
(let ((cb (current-buffer))
(tlp orgqda--taglist-parameters)
(pos (point)))
(setq buffer-read-only nil)
(with-current-buffer orgqda--originating-buffer
(apply #'orgqda-list-tags (append '(nil) `(:buffer ,cb) tlp)))
(goto-char pos))
(orgqda-update-taglist-general)))
(defvar orgqda--current-sorting-args nil)
;;;###autoload
(defun orgqda-sort-taglist (&optional sort non-recursive)
"Sort current taglist using ‘org-sort-entries’.
Sorts current subtree and children, active region, or children of
first headline if before that.
Sorting is determined via symbol SORT given by
‘orgqda-sort-parameters’. With NON-RECURSIVE non-nil, only sorts
the direct descendants of current headline, and not their
children."
(interactive (list (orgqda--read-sort-choice)))
(let* ((inhibit-read-only t)
(inhibit-message t)
(sort (or sort orgqda-default-sort-order))
(sortlist
(list
(when (not (member sort '(a-z z-a)))
(orgqda--org-sort-params 'a-z))
(orgqda--org-sort-params sort))))
(if (region-active-p)
;; don’t do double sort here, too difficult keeping region
(apply #'org-sort-entries (cadr sortlist))
(when (org-before-first-heading-p)
(outline-next-heading))
(unless (org-at-heading-p)
(org-back-to-heading t))
(dolist (so sortlist)
(when-let ((orgqda--current-sorting-args so))
(if non-recursive
(orgqda--sort-subtree)
(org-map-entries #'orgqda--sort-subtree t 'tree))))))
(when orgqda-list-mode
(setq orgqda--taglist-parameters
(plist-put orgqda--taglist-parameters :sort sort))))
;;;###autoload
(defun orgqda-sort-taglist-buffer (&optional sort)
"Sort the current taglist buffer.
calls ‘orgqda-sort-taglist’ for whole buffer.
Sort by SORT."
(interactive (list (orgqda--read-sort-choice)))
(save-mark-and-excursion
(while (org-up-heading-safe))
(when (or (org-goto-sibling)
(org-goto-sibling t))
(goto-char (point-min))
(set-mark (point-max)))
(funcall #'orgqda-sort-taglist sort)))
;;;;; Commands for collecting
;;;###autoload
(defun orgqda-collect-tagged (&optional match deeper-view buffer noswitch)
"Collect all segments marked with tags matching MATCH.
Display them in custom buffer in other window, and enable
‘orgqda-view-mode’ and ‘view-mode’. In an interactive call, MATCH is
prompted for.
For non-interactive use: DEEPER-VIEW (integer) adds visible
levels to folding with ‘org-content’. BUFFER specifies a buffer
to insert the collected tags in. NOSWITCH non-nil means no buffer
switching is done and view buffer just returned."
(interactive)
(let* ((matcher (orgqda--make-tags-matcher match))
(mname (car matcher))
(cont (orgqda--coll-tagged matcher 2))
(oclevel
(+ (if (and orgqda-collect-from-all-files orgqda-tag-files) 2 1)
(or deeper-view 0)))
(origbuf (or (when (buffer-live-p orgqda--originating-buffer)
orgqda--originating-buffer)
(current-buffer)))
(buffer (or buffer (generate-new-buffer
(format "*tags:%s*" mname)))))
(if (equal cont '(0))
(user-error "No matches for \"%s\"" mname)
(with-current-buffer buffer
(org-insert-time-stamp (current-time) t t
(format "* Tagged: %s, (%d) " mname (car cont)) "\n")
(insert (cdr cont))
(goto-char (point-min))
(org-mode)
(orgqda-view-mode)
(view-mode)
(orgqda--clone-local-variables origbuf)
(setq orgqda--current-search match
orgqda--originating-buffer origbuf)
(org-content oclevel))
(if noswitch
buffer
(pop-to-buffer buffer)))))
(defun orgqda-revert-collected-tags ()
"Revert current tag collection buffer by redoing search."
(interactive)
(when orgqda--current-search
(let ((inhibit-read-only t)
(cb (current-buffer))
(pos (point))
(cs orgqda--current-search))
(widen)
(delete-region (point-min) (point-max))
(orgqda--with-current-buffer-if orgqda--originating-buffer
(orgqda-collect-tagged cs nil cb t))
(goto-char pos))))
(defun orgqda-tag-in-collection-buffer ()
"Set tags of collected extracts remotely.
Stand-in for ‘org-set-tags-command’."
(interactive)
(when orgqda-view-mode
(when-let ((opbmlink (save-excursion
(and (org-back-to-heading)
(search-forward "[[opbm:" (line-end-position) t)
(org-element-context)))))
(let ((bm (cons "n" (read (org-link-decode (org-link-unescape (org-element-property :path opbmlink)))))))
(with-current-buffer (find-file-noselect (bookmark-get-filename bm))
(bookmark-default-handler bm)
(org-set-tags-command))
(orgqda-revert-collected-tags)))))
(defvar orgqda--csv-curr-mname nil)
;;;###autoload
(defun orgqda-collect-tagged-csv (&optional match)
"Collect tagged paragraphs for csv export, use MATCH for matching."
(interactive)
(let* ((matcher (orgqda--make-tags-matcher match))
(orgqda--csv-curr-mname (car matcher))
(cont (orgqda--coll-tagged-csv matcher)))
(pop-to-buffer
(generate-new-buffer (format "*csvtags:%s*" orgqda--csv-curr-mname)))
(when orgqda-convert-csv-to-encoding
(orgqda--csv-convert-buffer-to-encoding))
(insert cont)
(goto-char (point-min))))
;;;###autoload
(defun orgqda-collect-tagged-csv-save (&optional match)
"Collect and save a file in ‘orgqda-csv-dir’, use MATCH for matching."
(interactive)
(let* ((matcher (orgqda--make-tags-matcher match))
(orgqda--csv-curr-mname (car matcher))
(cont (orgqda--coll-tagged-csv matcher))
(current-csv-dir orgqda-csv-dir))
(with-temp-buffer
(insert cont)
(when orgqda-convert-csv-to-encoding
(orgqda--csv-convert-buffer-to-encoding))
(unless nil
(write-region (point-min) (point-max)
(expand-file-name
(concat orgqda--csv-curr-mname ".csv"
current-csv-dir)))))))
;;;###autoload
(defun orgqda-collect-tagged-csv-save-all (&optional threshold)
"Save all tags used THRESHOLD or more times to csv-files.
One csv-file per tag is generated in ‘orgqda-csv-dir’."
(interactive "P")
(let ((tags (orgqda--get-tags-hash))
(tn (prefix-numeric-value threshold)))
(maphash (lambda (tag count)
(when (or (not threshold)
(<= tn count))
(orgqda-collect-tagged-csv-save tag)))
tags)))
;;;;; Commands for renaming tags
(defun orgqda-drag-merge-tags (ev)
"Merge tags via dragging in tag listing buffer.
EV is the mouse event."
(interactive "e")
(let* ((start (event-start ev))
(end (event-end ev))
(s (posn-point start))
(e (posn-point end))
(s-tag (orgqda--tag-at-point s))
(e-tag (orgqda--tag-at-point e)))
(when (and s-tag e-tag
(eq (posn-window start) (posn-window end)))
(with-selected-window (posn-window start)
(orgqda--refile-and-merge s e s-tag e-tag)))))
(defun orgqda-refile-and-merge-tags (arg)
"Merge tags via refile selection (in codebook).
A prefix ARG does a normal ‘org-refile’."
(interactive "P")
(if arg
(org-refile)
(when-let* ((s (point))
(s-tag (orgqda--otag-at-this-headline))
(org-refile-targets '((nil :maxlevel . 8)))
(newloc (org-refile-get-location "Refile and merge tags to: "))
(e (nth 3 newloc))
(e-tag (org-with-wide-buffer
(goto-char e)
(orgqda--otag-at-this-headline))))
(orgqda--refile-and-merge s e s-tag e-tag))))
(defun orgqda-rename-tag (oldname newname)
"Rename tag OLDNAME to NEWNAME in current orgqda files."
(interactive (list
(orgqda--completing-read-tag "Old tag name: " (orgqda--tag-at-point nil t) t)
(orgqda--completing-read-tag "New tag name: " nil nil t)))
(if newname
(orgqda--delete-or-rename-tag oldname newname)
(user-error "Not renaming! No new tag name!")))
(defun orgqda-delete-tag (tagname)
"Delete tag TAGNAME in current orgqda files."
(interactive (list (orgqda--completing-read-tag
"Tag to delete: "
(orgqda--tag-at-point nil t)
t)))
(orgqda--delete-or-rename-tag tagname nil))
(defun orgqda-prefix-tag (oldname prefix)
"Add a prefix PREFIX to existing tag OLDNAME.
Works on all current orgqda files."
(interactive (list
(orgqda--completing-read-tag "Old tag name: " (orgqda--tag-at-point nil t) t)
(orgqda--completing-read-prefix
"Prefix: "
nil nil
;; if we completed tags with helm we need to fetch a clean list
(unless (bound-and-true-p orgqda-helm-tags-mode)))))
(orgqda-rename-tag oldname (concat prefix orgqda-hierarchy-delimiter oldname)))
(defun orgqda-rename-prefix-on-one-tag (oldname newprefix)
"Rename the prefix(es) of tag OLDNAME to NEWPREFIX."
(interactive (list
(orgqda--completing-read-tag "Old tag name: "
(orgqda--tag-at-point nil t) t)
(orgqda--completing-read-prefix
"New prefix: "
nil nil
;; if we completed tags with helm we need to fetch a clean list
(unless (bound-and-true-p orgqda-helm-tags-mode)))))
(orgqda-rename-tag oldname (orgqda--new-tag-from-new-prefix oldname newprefix)))
(defun orgqda--new-tag-from-new-prefix (oldname newprefix)
"Get new tagname when renaming OLDNAME with NEWPREFIX."
(when-let ((tagleaf
(car-safe (last (split-string oldname
orgqda-hierarchy-delimiter)))))
(concat newprefix orgqda-hierarchy-delimiter tagleaf)))
(defun orgqda-rename-prefix (oldprefix newprefix &optional taglist)
"Rename OLDPREFIX to NEWPREFIX for all tags using it in current orgqda files.
TAGLIST can be passed as the list of tags to replace on."
(interactive (list
(orgqda--completing-read-prefix "Old prefix: " (orgqda--tag-prefix-at-point) t)
(orgqda--completing-read-prefix "New prefix: " nil nil t)
(orgqda--get-tags-for-completion t)))
(cl-loop for (tag) in taglist
when (string-prefix-p oldprefix tag)
do (orgqda-rename-tag
tag
(concat newprefix (string-remove-prefix oldprefix tag)))))
;;;; Navigating to codebook
(defun orgqda-find-tag-in-codebook (tag)
"Navigate to tag TAG in ‘orgqda-codebook-file’."
(interactive (list (completing-read "Tag to to find in codebook: "
(orgqda--get-tags-for-completion)
nil nil
(orgqda--tag-at-point))))
(when (and orgqda-codebook-file (file-readable-p orgqda-codebook-file))
(find-file orgqda-codebook-file)
(orgqda--find-otag-link tag)))
(defun orgqda--find-otag-link (tag &optional pass-error)
"Go to first otag link to TAG in current buffer.
Only reports errors if PASS-ERROR is non-nil."
(widen)
(goto-char (point-min))
(when (search-forward-regexp (concat "\\[\\[otag:" tag) nil (not pass-error))
(beginning-of-line)
(pulse-momentary-highlight-one-line (point))))
;;;; Code relations functionality
(defvar orgqda--tag-relations-hash (make-hash-table :test 'equal)
"Hash table for tag-relations.")
(defun orgqda-view-tag-relations (k)
"Display occurrences of co-tagging.
Numeric prefix arg K defines which tuples to count"
(interactive "p")
(let ((origbuffer (current-buffer))
(origfile (buffer-file-name))
(k (if (< k 2) 2 k)))
(orgqda--collect-tag-relations k)
(pop-to-buffer
(generate-new-buffer "*orgqda-tag-relations*"))
(org-insert-time-stamp (current-time) t t
(format
"* Orgqda %d-tag-relations generated from %s at "
k
(org-link-make-string
(concat "file:" origfile)
(buffer-name origbuffer)))
"\n")
(cl-loop for (combo . count)
in (cl-sort (orgqda--hash-to-alist orgqda--tag-relations-hash) #'> :key #'cdr)
do (insert (format "** [[otag:%s%s][%s]] (%d)\n"
combo
(and orgqda-taglink-include-filename
(concat "::" origfile))
(replace-regexp-in-string "\\+" " + " combo)
count)))
(goto-char (point-min))
(org-mode) (view-mode) (orgqda-list-mode) (flyspell-mode -1)
(setq orgqda--originating-buffer origbuffer)))
(defun orgqda--collect-tag-relations (k)
"Collect tag relations between K tuples of tags in all orgqda files."
(clrhash orgqda--tag-relations-hash)
(org-map-entries
(lambda () (orgqda--get-tag-relations-k k))
nil
(or
(and orgqda-collect-from-all-files (orgqda-tag-files))
(when-let ((bfn
(or (buffer-file-name)
(buffer-file-name
(buffer-base-buffer)))))
(list bfn)))
'archive 'comment))
;; Inspiration from:
;; https://www.geeksforgeeks.org/print-subsets-given-size-set/
(defun orgqda--get-tag-relations-k (k)
"Get tag relations for all K tuples of tags at point."
(when-let ((taglist (org-get-tags nil t))
(taglist (sort taglist #'string-lessp))
(n (length taglist)))