Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-mouse.el
blob45b4d5604b59625161c2e3834364bc9801b9f8f5
1 ;;; org-mouse.el --- Better mouse support for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2006-2018 Free Software Foundation, Inc.
5 ;; Author: Piotr Zielinski <piotr dot zielinski at gmail dot com>
6 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Org-mouse provides mouse support for org-mode.
27 ;; https://orgmode.org
29 ;; Org mouse implements the following features:
30 ;; * following links with the left mouse button
31 ;; * subtree expansion/collapse (org-cycle) with the left mouse button
32 ;; * several context menus on the right mouse button:
33 ;; + general text
34 ;; + headlines
35 ;; + timestamps
36 ;; + priorities
37 ;; + links
38 ;; + tags
39 ;; * promoting/demoting/moving subtrees with mouse-3
40 ;; + if the drag starts and ends in the same line then promote/demote
41 ;; + otherwise move the subtree
43 ;; Use
44 ;; ---
46 ;; To use this package, put the following line in your .emacs:
48 ;; (require 'org-mouse)
51 ;; FIXME:
52 ;; + deal with folding / unfolding issues
54 ;; TODO (This list is only theoretical, if you'd like to have some
55 ;; feature implemented or a bug fix please send me an email, even if
56 ;; something similar appears in the list below. This will help me get
57 ;; the priorities right.):
59 ;; + org-store-link, insert link
60 ;; + org tables
61 ;; + occur with the current word/tag (same menu item)
62 ;; + ctrl-c ctrl-c, for example, renumber the current list
63 ;; + internal links
65 ;; Please email the maintainer with new feature suggestions / bugs
67 ;; History:
69 ;; Since version 5.10: Changes are listed in the general Org docs.
71 ;; Version 5.09;; + Version number synchronization with Org mode.
73 ;; Version 0.25
74 ;; + made compatible with Org 4.70 (thanks to Carsten for the patch)
76 ;; Version 0.24
77 ;; + minor changes to the table menu
79 ;; Version 0.23
80 ;; + preliminary support for tables and calculation marks
81 ;; + context menu support for org-agenda-undo & org-sort-entries
83 ;; Version 0.22
84 ;; + handles undo support for the agenda buffer (requires Org >=4.58)
86 ;; Version 0.21
87 ;; + selected text activates its context menu
88 ;; + shift-middleclick or right-drag inserts the text from the clipboard in the form of a link
90 ;; Version 0.20
91 ;; + the new "TODO Status" submenu replaces the "Cycle TODO" menu item
92 ;; + the TODO menu can now list occurrences of a specific TODO keyword
93 ;; + #+STARTUP line is now recognized
95 ;; Version 0.19
96 ;; + added support for dragging URLs to the org-buffer
98 ;; Version 0.18
99 ;; + added support for agenda blocks
101 ;; Version 0.17
102 ;; + toggle checkboxes with a single click
104 ;; Version 0.16
105 ;; + added support for checkboxes
107 ;; Version 0.15
108 ;; + Org now works with the Agenda buffer as well
110 ;; Version 0.14
111 ;; + added a menu option that converts plain list items to outline items
113 ;; Version 0.13
114 ;; + "Insert Heading" now inserts a sibling heading if the point is
115 ;; on "***" and a child heading otherwise
117 ;; Version 0.12
118 ;; + compatible with Emacs 21
119 ;; + custom agenda commands added to the main menu
120 ;; + moving trees should now work between windows in the same frame
122 ;; Version 0.11
123 ;; + fixed org-mouse-at-link (thanks to Carsten)
124 ;; + removed [follow-link] bindings
126 ;; Version 0.10
127 ;; + added a menu option to remove highlights
128 ;; + compatible with Org 4.21 now
130 ;; Version 0.08:
131 ;; + trees can be moved/promoted/demoted by dragging with the right
132 ;; mouse button (mouse-3)
133 ;; + small changes in the above function
135 ;; Versions 0.01 -- 0.07: (I don't remember)
137 ;;; Code:
139 (require 'org)
140 (require 'cl-lib)
142 (defvar org-agenda-allow-remote-undo)
143 (defvar org-agenda-undo-list)
144 (defvar org-agenda-custom-commands)
145 (declare-function org-agenda-change-all-lines "org-agenda"
146 (newhead hdmarker &optional fixface just-this))
147 (declare-function org-verify-change-for-undo "org-agenda" (l1 l2))
148 (declare-function org-apply-on-list "org-list" (function init-value &rest args))
149 (declare-function org-agenda-earlier "org-agenda" (arg))
150 (declare-function org-agenda-later "org-agenda" (arg))
152 (defvar org-mouse-main-buffer nil
153 "Active buffer for mouse operations.")
154 (defvar org-mouse-plain-list-regexp "\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
155 "Regular expression that matches a plain list.")
156 (defvar org-mouse-direct t
157 "Internal variable indicating whether the current action is direct.
159 If t, then the current action has been invoked directly through the buffer
160 it is intended to operate on. If nil, then the action has been invoked
161 indirectly, for example, through the agenda buffer.")
163 (defgroup org-mouse nil
164 "Mouse support for org-mode."
165 :tag "Org Mouse"
166 :group 'org)
168 (defcustom org-mouse-punctuation ":"
169 "Punctuation used when inserting text by drag and drop."
170 :group 'org-mouse
171 :type 'string)
173 (defcustom org-mouse-features
174 '(context-menu yank-link activate-stars activate-bullets activate-checkboxes)
175 "The features of org-mouse that should be activated.
176 Changing this variable requires a restart of Emacs to get activated."
177 :group 'org-mouse
178 :type '(set :greedy t
179 (const :tag "Mouse-3 shows context menu" context-menu)
180 (const :tag "C-mouse-1 and mouse-3 move trees" move-tree)
181 (const :tag "S-mouse-2 and drag-mouse-3 yank link" yank-link)
182 (const :tag "Activate headline stars" activate-stars)
183 (const :tag "Activate item bullets" activate-bullets)
184 (const :tag "Activate checkboxes" activate-checkboxes)))
186 (defun org-mouse-re-search-line (regexp)
187 "Search the current line for a given regular expression."
188 (beginning-of-line)
189 (re-search-forward regexp (point-at-eol) t))
191 (defun org-mouse-end-headline ()
192 "Go to the end of current headline (ignoring tags)."
193 (interactive)
194 (end-of-line)
195 (skip-chars-backward "\t ")
196 (when (looking-back ":[A-Za-z]+:" (line-beginning-position))
197 (skip-chars-backward ":A-Za-z")
198 (skip-chars-backward "\t ")))
200 (defvar-local org-mouse-context-menu-function nil
201 "Function to create the context menu.
202 The value of this variable is the function invoked by
203 `org-mouse-context-menu' as the context menu.")
205 (defun org-mouse-show-context-menu (event prefix)
206 "Invoke the context menu.
208 If the value of `org-mouse-context-menu-function' is a function, then
209 this function is called. Otherwise, the current major mode menu is used."
210 (interactive "@e \nP")
211 (if (and (= (event-click-count event) 1)
212 (or (not mark-active)
213 (sit-for (/ double-click-time 1000.0))))
214 (progn
215 (select-window (posn-window (event-start event)))
216 (when (not (org-mouse-mark-active))
217 (goto-char (posn-point (event-start event)))
218 (when (not (eolp)) (save-excursion (run-hooks 'post-command-hook)))
219 (sit-for 0))
220 (if (functionp org-mouse-context-menu-function)
221 (funcall org-mouse-context-menu-function event)
222 (if (fboundp 'mouse-menu-major-mode-map)
223 (popup-menu (mouse-menu-major-mode-map) event prefix)
224 (with-no-warnings ; don't warn about fallback, obsolete since 23.1
225 (mouse-major-mode-menu event prefix)))))
226 (setq this-command 'mouse-save-then-kill)
227 (mouse-save-then-kill event)))
229 (defun org-mouse-line-position ()
230 "Return `:beginning' or `:middle' or `:end', depending on the point position.
232 If the point is at the end of the line, return `:end'.
233 If the point is separated from the beginning of the line only by white
234 space and *'s (`org-mouse-bolp'), return `:beginning'. Otherwise,
235 return `:middle'."
236 (cond
237 ((eolp) :end)
238 ((org-mouse-bolp) :beginning)
239 (t :middle)))
241 (defun org-mouse-empty-line ()
242 "Return non-nil iff the line contains only white space."
243 (save-excursion (beginning-of-line) (looking-at "[ \t]*$")))
245 (defun org-mouse-next-heading ()
246 "Go to the next heading.
247 If there is none, ensure that the point is at the beginning of an empty line."
248 (unless (outline-next-heading)
249 (beginning-of-line)
250 (unless (org-mouse-empty-line)
251 (end-of-line)
252 (newline))))
254 (defun org-mouse-insert-heading ()
255 "Insert a new heading, as `org-insert-heading'.
257 If the point is at the :beginning (`org-mouse-line-position') of the line,
258 insert the new heading before the current line. Otherwise, insert it
259 after the current heading."
260 (interactive)
261 (cl-case (org-mouse-line-position)
262 (:beginning (beginning-of-line)
263 (org-insert-heading))
264 (t (org-mouse-next-heading)
265 (org-insert-heading))))
267 (defun org-mouse-timestamp-today (&optional shift units)
268 "Change the timestamp into SHIFT UNITS in the future.
270 For the acceptable UNITS, see `org-timestamp-change'."
271 (interactive)
272 (org-time-stamp nil)
273 (when shift (org-timestamp-change shift units)))
275 (defun org-mouse-keyword-menu (keywords function &optional selected itemformat)
276 "A helper function.
278 Returns a menu fragment consisting of KEYWORDS. When a keyword
279 is selected by the user, FUNCTION is called with the selected
280 keyword as the only argument.
282 If SELECTED is nil, then all items are normal menu items. If
283 SELECTED is a function, then each item is a checkbox, which is
284 enabled for a given keyword iff (funcall SELECTED keyword) return
285 non-nil. If SELECTED is neither nil nor a function, then the
286 items are radio buttons. A radio button is enabled for the
287 keyword `equal' to SELECTED.
289 ITEMFORMAT governs formatting of the elements of KEYWORDS. If it
290 is a function, it is invoked with the keyword as the only
291 argument. If it is a string, it is interpreted as the format
292 string to (format ITEMFORMAT keyword). If it is neither a string
293 nor a function, elements of KEYWORDS are used directly."
294 (mapcar
295 `(lambda (keyword)
296 (vector (cond
297 ((functionp ,itemformat) (funcall ,itemformat keyword))
298 ((stringp ,itemformat) (format ,itemformat keyword))
299 (t keyword))
300 (list 'funcall ,function keyword)
301 :style (cond
302 ((null ,selected) t)
303 ((functionp ,selected) 'toggle)
304 (t 'radio))
305 :selected (if (functionp ,selected)
306 (and (funcall ,selected keyword) t)
307 (equal ,selected keyword))))
308 keywords))
310 (defun org-mouse-remove-match-and-spaces ()
311 "Remove the match, make just one space around the point."
312 (interactive)
313 (replace-match "")
314 (just-one-space))
316 (defvar org-mouse-rest)
317 (defun org-mouse-replace-match-and-surround
318 (_newtext &optional _fixedcase _literal _string subexp)
319 "The same as `replace-match', but surrounds the replacement with spaces."
320 (apply #'replace-match org-mouse-rest)
321 (save-excursion
322 (goto-char (match-beginning (or subexp 0)))
323 (just-one-space)
324 (goto-char (match-end (or subexp 0)))
325 (just-one-space)))
327 (defun org-mouse-keyword-replace-menu (keywords &optional group itemformat
328 nosurround)
329 "A helper function.
331 Returns a menu fragment consisting of KEYWORDS. When a keyword
332 is selected, group GROUP of the current match is replaced by the
333 keyword. The method ensures that both ends of the replacement
334 are separated from the rest of the text in the buffer by
335 individual spaces (unless NOSURROUND is non-nil).
337 The final entry of the menu is always \"None\", which removes the
338 match.
340 ITEMFORMAT governs formatting of the elements of KEYWORDS. If it
341 is a function, it is invoked with the keyword as the only
342 argument. If it is a string, it is interpreted as the format
343 string to (format ITEMFORMAT keyword). If it is neither a string
344 nor a function, elements of KEYWORDS are used directly."
345 (setq group (or group 0))
346 (let ((replace (org-mouse-match-closure
347 (if nosurround 'replace-match
348 'org-mouse-replace-match-and-surround))))
349 (append
350 (org-mouse-keyword-menu
351 keywords
352 `(lambda (keyword) (funcall ,replace keyword t t nil ,group))
353 (match-string group)
354 itemformat)
355 `(["None" org-mouse-remove-match-and-spaces
356 :style radio
357 :selected ,(not (member (match-string group) keywords))]))))
359 (defun org-mouse-show-headlines ()
360 "Change the visibility of the current org buffer to only show headlines."
361 (interactive)
362 (let ((this-command 'org-cycle)
363 (last-command 'org-cycle)
364 (org-cycle-global-status nil))
365 (org-cycle '(4))
366 (org-cycle '(4))))
368 (defun org-mouse-show-overview ()
369 "Change visibility of current org buffer to first-level headlines only."
370 (interactive)
371 (let ((org-cycle-global-status nil))
372 (org-cycle '(4))))
374 (defun org-mouse-set-priority (priority)
375 "Set the priority of the current headline to PRIORITY."
376 (org-priority priority))
378 (defvar org-mouse-priority-regexp "\\[#\\([A-Z]\\)\\]"
379 "Regular expression matching the priority indicator.
380 Differs from `org-priority-regexp' in that it doesn't contain the
381 leading `.*?'.")
383 (defun org-mouse-get-priority (&optional default)
384 "Return the priority of the current headline.
385 DEFAULT is returned if no priority is given in the headline."
386 (save-excursion
387 (if (org-mouse-re-search-line org-mouse-priority-regexp)
388 (match-string 1)
389 (when default (char-to-string org-default-priority)))))
391 (defun org-mouse-delete-timestamp ()
392 "Deletes the current timestamp as well as the preceding keyword.
393 SCHEDULED: or DEADLINE: or ANYTHINGLIKETHIS:"
394 (when (or (org-at-date-range-p) (org-at-timestamp-p 'lax))
395 (replace-match "") ;delete the timestamp
396 (skip-chars-backward " :A-Z")
397 (when (looking-at " *[A-Z][A-Z]+:")
398 (replace-match ""))))
400 (defun org-mouse-looking-at (regexp skipchars &optional movechars)
401 (save-excursion
402 (let ((point (point)))
403 (if (looking-at regexp) t
404 (skip-chars-backward skipchars)
405 (forward-char (or movechars 0))
406 (when (looking-at regexp)
407 (> (match-end 0) point))))))
409 (defun org-mouse-priority-list ()
410 (cl-loop for priority from ?A to org-lowest-priority
411 collect (char-to-string priority)))
413 (defun org-mouse-todo-menu (state)
414 "Create the menu with TODO keywords."
415 (append
416 (let ((kwds org-todo-keywords-1))
417 (org-mouse-keyword-menu
418 kwds
419 `(lambda (kwd) (org-todo kwd))
420 (lambda (kwd) (equal state kwd))))))
422 (defun org-mouse-tag-menu () ;todo
423 "Create the tags menu."
424 (append
425 (let ((tags (org-get-tags nil t)))
426 (org-mouse-keyword-menu
427 (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp)
428 `(lambda (tag)
429 (org-mouse-set-tags
430 (sort (if (member tag (quote ,tags))
431 (delete tag (quote ,tags))
432 (cons tag (quote ,tags)))
433 'string-lessp)))
434 `(lambda (tag) (member tag (quote ,tags)))
436 '("--"
437 ["Align Tags Here" (org-align-tags) t]
438 ["Align Tags in Buffer" (org-align-tags t) t]
439 ["Set Tags ..." (org-set-tags-command) t])))
441 (defun org-mouse-set-tags (tags)
442 (org-set-tags tags))
444 (defun org-mouse-insert-checkbox ()
445 (interactive)
446 (and (org-at-item-p)
447 (goto-char (match-end 0))
448 (unless (org-at-item-checkbox-p)
449 (delete-horizontal-space)
450 (insert " [ ] "))))
452 (defun org-mouse-agenda-type (type)
453 (pcase type
454 (`tags "Tags: ")
455 (`todo "TODO: ")
456 (`tags-tree "Tags tree: ")
457 (`todo-tree "TODO tree: ")
458 (`occur-tree "Occur tree: ")
459 (_ "Agenda command ???")))
461 (defun org-mouse-list-options-menu (alloptions &optional function)
462 (let ((options (save-match-data
463 (split-string (match-string-no-properties 1)))))
464 (print options)
465 (cl-loop for name in alloptions
466 collect
467 (vector name
468 `(progn
469 (replace-match
470 (mapconcat 'identity
471 (sort (if (member ',name ',options)
472 (delete ',name ',options)
473 (cons ',name ',options))
474 'string-lessp)
475 " ")
476 nil nil nil 1)
477 (when (functionp ',function) (funcall ',function)))
478 :style 'toggle
479 :selected (and (member name options) t)))))
481 (defun org-mouse-clip-text (text maxlength)
482 (if (> (length text) maxlength)
483 (concat (substring text 0 (- maxlength 3)) "...")
484 text))
486 (defun org-mouse-popup-global-menu ()
487 (popup-menu
488 `("Main Menu"
489 ["Show Overview" org-mouse-show-overview t]
490 ["Show Headlines" org-mouse-show-headlines t]
491 ["Show All" org-show-all t]
492 ["Remove Highlights" org-remove-occur-highlights
493 :visible org-occur-highlights]
494 "--"
495 ["Check Deadlines"
496 (if (functionp 'org-check-deadlines-and-todos)
497 (org-check-deadlines-and-todos org-deadline-warning-days)
498 (org-check-deadlines org-deadline-warning-days)) t]
499 ["Check TODOs" org-show-todo-tree t]
500 ("Check Tags"
501 ,@(org-mouse-keyword-menu
502 (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp)
503 #'(lambda (tag) (org-tags-sparse-tree nil tag)))
504 "--"
505 ["Custom Tag ..." org-tags-sparse-tree t])
506 ["Check Phrase ..." org-occur]
507 "--"
508 ["Display Agenda" org-agenda-list t]
509 ["Display TODO List" org-todo-list t]
510 ("Display Tags"
511 ,@(org-mouse-keyword-menu
512 (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp)
513 #'(lambda (tag) (org-tags-view nil tag)))
514 "--"
515 ["Custom Tag ..." org-tags-view t])
516 ["Display Calendar" org-goto-calendar t]
517 "--"
518 ,@(org-mouse-keyword-menu
519 (mapcar 'car org-agenda-custom-commands)
520 #'(lambda (key)
521 (eval `(org-agenda nil (string-to-char ,key))))
523 #'(lambda (key)
524 (let ((entry (assoc key org-agenda-custom-commands)))
525 (org-mouse-clip-text
526 (cond
527 ((stringp (nth 1 entry)) (nth 1 entry))
528 ((stringp (nth 2 entry))
529 (concat (org-mouse-agenda-type (nth 1 entry))
530 (nth 2 entry)))
531 (t "Agenda Command `%s'"))
532 30))))
533 "--"
534 ["Delete Blank Lines" delete-blank-lines
535 :visible (org-mouse-empty-line)]
536 ["Insert Checkbox" org-mouse-insert-checkbox
537 :visible (and (org-at-item-p) (not (org-at-item-checkbox-p)))]
538 ["Insert Checkboxes"
539 (org-mouse-for-each-item 'org-mouse-insert-checkbox)
540 :visible (and (org-at-item-p) (not (org-at-item-checkbox-p)))]
541 ["Plain List to Outline" org-mouse-transform-to-outline
542 :visible (org-at-item-p)])))
544 (defun org-mouse-get-context (contextlist context)
545 (let ((contextdata (assq context contextlist)))
546 (when contextdata
547 (save-excursion
548 (goto-char (nth 1 contextdata))
549 (re-search-forward ".*" (nth 2 contextdata))))))
551 (defun org-mouse-for-each-item (funct)
552 ;; Functions called by `org-apply-on-list' need an argument.
553 (let ((wrap-fun (lambda (_) (funcall funct))))
554 (when (ignore-errors (goto-char (org-in-item-p)))
555 (save-excursion (org-apply-on-list wrap-fun nil)))))
557 (defun org-mouse-bolp ()
558 "Return true if there only spaces, tabs, and `*' before point.
559 This means, between the beginning of line and the point."
560 (save-excursion
561 (skip-chars-backward " \t*") (bolp)))
563 (defun org-mouse-insert-item (text)
564 (cl-case (org-mouse-line-position)
565 (:beginning ; insert before
566 (beginning-of-line)
567 (looking-at "[ \t]*")
568 (open-line 1)
569 (indent-to-column (- (match-end 0) (match-beginning 0)))
570 (insert "+ "))
571 (:middle ; insert after
572 (end-of-line)
573 (newline t)
574 (indent-relative)
575 (insert "+ "))
576 (:end ; insert text here
577 (skip-chars-backward " \t")
578 (kill-region (point) (point-at-eol))
579 (unless (looking-back org-mouse-punctuation (line-beginning-position))
580 (insert (concat org-mouse-punctuation " ")))))
581 (insert text)
582 (beginning-of-line))
584 (defadvice dnd-insert-text (around org-mouse-dnd-insert-text activate)
585 (if (derived-mode-p 'org-mode)
586 (org-mouse-insert-item text)
587 ad-do-it))
589 (defadvice dnd-open-file (around org-mouse-dnd-open-file activate)
590 (if (derived-mode-p 'org-mode)
591 (org-mouse-insert-item uri)
592 ad-do-it))
594 (defun org-mouse-match-closure (function)
595 (let ((match (match-data t)))
596 `(lambda (&rest rest)
597 (save-match-data
598 (set-match-data ',match)
599 (apply ',function rest)))))
601 (defun org-mouse-yank-link (click)
602 (interactive "e")
603 ;; Give temporary modes such as isearch a chance to turn off.
604 (run-hooks 'mouse-leave-buffer-hook)
605 (mouse-set-point click)
606 (setq mouse-selection-click-count 0)
607 (delete-horizontal-space)
608 (insert-for-yank (concat " [[" (current-kill 0) "]] ")))
610 (defun org-mouse-context-menu (&optional event)
611 (let* ((stamp-prefixes (list org-deadline-string org-scheduled-string))
612 (contextlist (org-context))
613 (get-context (lambda (context) (org-mouse-get-context contextlist context))))
614 (cond
615 ((org-mouse-mark-active)
616 (let ((region-string (buffer-substring (region-beginning) (region-end))))
617 (popup-menu
618 `(nil
619 ["Sparse Tree" (org-occur ',region-string)]
620 ["Find in Buffer" (occur ',region-string)]
621 ["Grep in Current Dir"
622 (grep (format "grep -rnH -e '%s' *" ',region-string))]
623 ["Grep in Parent Dir"
624 (grep (format "grep -rnH -e '%s' ../*" ',region-string))]
625 "--"
626 ["Convert to Link"
627 (progn (save-excursion (goto-char (region-beginning)) (insert "[["))
628 (save-excursion (goto-char (region-end)) (insert "]]")))]
629 ["Insert Link Here" (org-mouse-yank-link ',event)]))))
630 ((save-excursion (beginning-of-line) (looking-at "[ \t]*#\\+STARTUP: \\(.*\\)"))
631 (popup-menu
632 `(nil
633 ,@(org-mouse-list-options-menu (mapcar 'car org-startup-options)
634 'org-mode-restart))))
635 ((or (eolp)
636 (and (looking-at "\\( \\|\t\\)\\(+:[0-9a-zA-Z_:]+\\)?\\( \\|\t\\)+$")
637 (looking-back " \\|\t" (- (point) 2)
638 (line-beginning-position))))
639 (org-mouse-popup-global-menu))
640 ((funcall get-context :checkbox)
641 (popup-menu
642 '(nil
643 ["Toggle" org-toggle-checkbox t]
644 ["Remove" org-mouse-remove-match-and-spaces t]
646 ["All Clear" (org-mouse-for-each-item
647 (lambda ()
648 (when (save-excursion (org-at-item-checkbox-p))
649 (replace-match "[ ] "))))]
650 ["All Set" (org-mouse-for-each-item
651 (lambda ()
652 (when (save-excursion (org-at-item-checkbox-p))
653 (replace-match "[X] "))))]
654 ["All Toggle" (org-mouse-for-each-item 'org-toggle-checkbox) t]
655 ["All Remove" (org-mouse-for-each-item
656 (lambda ()
657 (when (save-excursion (org-at-item-checkbox-p))
658 (org-mouse-remove-match-and-spaces))))]
660 ((and (org-mouse-looking-at "\\b\\w+" "a-zA-Z0-9_")
661 (member (match-string 0) org-todo-keywords-1))
662 (popup-menu
663 `(nil
664 ,@(org-mouse-todo-menu (match-string 0))
665 "--"
666 ["Check TODOs" org-show-todo-tree t]
667 ["List all TODO keywords" org-todo-list t]
668 [,(format "List only %s" (match-string 0))
669 (org-todo-list (match-string 0)) t]
671 ((and (org-mouse-looking-at "\\b[A-Z]+:" "A-Z")
672 (member (match-string 0) stamp-prefixes))
673 (popup-menu
674 `(nil
675 ,@(org-mouse-keyword-replace-menu stamp-prefixes)
676 "--"
677 ["Check Deadlines" org-check-deadlines t]
679 ((org-mouse-looking-at org-mouse-priority-regexp "[]A-Z#") ; priority
680 (popup-menu `(nil ,@(org-mouse-keyword-replace-menu
681 (org-mouse-priority-list) 1 "Priority %s" t))))
682 ((funcall get-context :link)
683 (popup-menu
684 '(nil
685 ["Open" org-open-at-point t]
686 ["Open in Emacs" (org-open-at-point t) t]
687 "--"
688 ["Copy link" (org-kill-new (match-string 0))]
689 ["Cut link"
690 (progn
691 (kill-region (match-beginning 0) (match-end 0))
692 (just-one-space))]
693 "--"
694 ["Grep for TODOs"
695 (grep (format "grep -nH -i 'todo\\|fixme' %s*" (match-string 2)))]
696 ; ["Paste file link" ((insert "file:") (yank))]
698 ((org-mouse-looking-at ":\\([A-Za-z0-9_]+\\):" "A-Za-z0-9_" -1) ;tags
699 (popup-menu
700 `(nil
701 [,(format-message "Display `%s'" (match-string 1))
702 (org-tags-view nil ,(match-string 1))]
703 [,(format-message "Sparse Tree `%s'" (match-string 1))
704 (org-tags-sparse-tree nil ,(match-string 1))]
705 "--"
706 ,@(org-mouse-tag-menu))))
707 ((org-at-timestamp-p 'lax)
708 (popup-menu
709 '(nil
710 ["Show Day" org-open-at-point t]
711 ["Change Timestamp" org-time-stamp t]
712 ["Delete Timestamp" (org-mouse-delete-timestamp) t]
713 ["Compute Time Range" org-evaluate-time-range (org-at-date-range-p)]
714 "--"
715 ["Set for Today" org-mouse-timestamp-today]
716 ["Set for Tomorrow" (org-mouse-timestamp-today 1 'day)]
717 ["Set in 1 Week" (org-mouse-timestamp-today 7 'day)]
718 ["Set in 2 Weeks" (org-mouse-timestamp-today 14 'day)]
719 ["Set in a Month" (org-mouse-timestamp-today 1 'month)]
720 "--"
721 ["+ 1 Day" (org-timestamp-change 1 'day)]
722 ["+ 1 Week" (org-timestamp-change 7 'day)]
723 ["+ 1 Month" (org-timestamp-change 1 'month)]
724 "--"
725 ["- 1 Day" (org-timestamp-change -1 'day)]
726 ["- 1 Week" (org-timestamp-change -7 'day)]
727 ["- 1 Month" (org-timestamp-change -1 'month)])))
728 ((funcall get-context :table-special)
729 (let ((mdata (match-data)))
730 (cl-incf (car mdata) 2)
731 (store-match-data mdata))
732 (message "match: %S" (match-string 0))
733 (popup-menu `(nil ,@(org-mouse-keyword-replace-menu
734 '(" " "!" "^" "_" "$" "#" "*" "'") 0
735 (lambda (mark)
736 (cl-case (string-to-char mark)
737 (? "( ) Nothing Special")
738 (?! "(!) Column Names")
739 (?^ "(^) Field Names Above")
740 (?_ "(^) Field Names Below")
741 (?$ "($) Formula Parameters")
742 (?# "(#) Recalculation: Auto")
743 (?* "(*) Recalculation: Manual")
744 (?' "(') Recalculation: None"))) t))))
745 ((assq :table contextlist)
746 (popup-menu
747 '(nil
748 ["Align Table" org-ctrl-c-ctrl-c]
749 ["Blank Field" org-table-blank-field]
750 ["Edit Field" org-table-edit-field]
751 "--"
752 ("Column"
753 ["Move Column Left" org-metaleft]
754 ["Move Column Right" org-metaright]
755 ["Delete Column" org-shiftmetaleft]
756 ["Insert Column" org-shiftmetaright]
757 "--"
758 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :selected org-table-limit-column-width :style toggle])
759 ("Row"
760 ["Move Row Up" org-metaup]
761 ["Move Row Down" org-metadown]
762 ["Delete Row" org-shiftmetaup]
763 ["Insert Row" org-shiftmetadown]
764 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
765 "--"
766 ["Insert Hline" org-table-insert-hline])
767 ("Rectangle"
768 ["Copy Rectangle" org-copy-special]
769 ["Cut Rectangle" org-cut-special]
770 ["Paste Rectangle" org-paste-special]
771 ["Fill Rectangle" org-table-wrap-region])
772 "--"
773 ["Set Column Formula" org-table-eval-formula]
774 ["Set Field Formula" (org-table-eval-formula '(4))]
775 ["Edit Formulas" org-table-edit-formulas]
776 "--"
777 ["Recalculate Line" org-table-recalculate]
778 ["Recalculate All" (org-table-recalculate '(4))]
779 ["Iterate All" (org-table-recalculate '(16))]
780 "--"
781 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks]
782 ["Sum Column/Rectangle" org-table-sum
783 :active (or (org-at-table-p) (org-region-active-p))]
784 ["Field Info" org-table-field-info]
785 ["Debug Formulas"
786 (setq org-table-formula-debug (not org-table-formula-debug))
787 :style toggle :selected org-table-formula-debug]
789 ((and (assq :headline contextlist) (not (eolp)))
790 (let ((priority (org-mouse-get-priority t)))
791 (popup-menu
792 `("Headline Menu"
793 ("Tags and Priorities"
794 ,@(org-mouse-keyword-menu
795 (org-mouse-priority-list)
796 #'(lambda (keyword)
797 (org-mouse-set-priority (string-to-char keyword)))
798 priority "Priority %s")
799 "--"
800 ,@(org-mouse-tag-menu))
801 ("TODO Status"
802 ,@(org-mouse-todo-menu (org-get-todo-state)))
803 ["Show Tags"
804 (with-current-buffer org-mouse-main-buffer (org-agenda-show-tags))
805 :visible (not org-mouse-direct)]
806 ["Show Priority"
807 (with-current-buffer org-mouse-main-buffer (org-agenda-show-priority))
808 :visible (not org-mouse-direct)]
809 ,@(if org-mouse-direct '("--") nil)
810 ["New Heading" org-mouse-insert-heading :visible org-mouse-direct]
811 ["Set Deadline"
812 (progn (org-mouse-end-headline) (insert " ") (org-deadline))
813 :active (not (save-excursion
814 (org-mouse-re-search-line org-deadline-regexp)))]
815 ["Schedule Task"
816 (progn (org-mouse-end-headline) (insert " ") (org-schedule))
817 :active (not (save-excursion
818 (org-mouse-re-search-line org-scheduled-regexp)))]
819 ["Insert Timestamp"
820 (progn (org-mouse-end-headline) (insert " ") (org-time-stamp nil)) t]
821 ; ["Timestamp (inactive)" org-time-stamp-inactive t]
822 "--"
823 ["Archive Subtree" org-archive-subtree]
824 ["Cut Subtree" org-cut-special]
825 ["Copy Subtree" org-copy-special]
826 ["Paste Subtree" org-paste-special :visible org-mouse-direct]
827 ("Sort Children"
828 ["Alphabetically" (org-sort-entries nil ?a)]
829 ["Numerically" (org-sort-entries nil ?n)]
830 ["By Time/Date" (org-sort-entries nil ?t)]
831 "--"
832 ["Reverse Alphabetically" (org-sort-entries nil ?A)]
833 ["Reverse Numerically" (org-sort-entries nil ?N)]
834 ["Reverse By Time/Date" (org-sort-entries nil ?T)])
835 "--"
836 ["Move Trees" org-mouse-move-tree :active nil]
837 ))))
839 (org-mouse-popup-global-menu)))))
841 (defun org-mouse-mark-active ()
842 (and mark-active transient-mark-mode))
844 (defun org-mouse-in-region-p (pos)
845 (and (org-mouse-mark-active)
846 (>= pos (region-beginning))
847 (< pos (region-end))))
849 (defun org-mouse-down-mouse (event)
850 (interactive "e")
851 (setq this-command last-command)
852 (unless (and (= 1 (event-click-count event))
853 (org-mouse-in-region-p (posn-point (event-start event))))
854 (mouse-drag-region event)))
856 (add-hook 'org-mode-hook
857 #'(lambda ()
858 (setq org-mouse-context-menu-function 'org-mouse-context-menu)
860 (when (memq 'context-menu org-mouse-features)
861 (org-defkey org-mouse-map [mouse-3] nil)
862 (org-defkey org-mode-map [mouse-3] 'org-mouse-show-context-menu))
863 (org-defkey org-mode-map [down-mouse-1] 'org-mouse-down-mouse)
864 (when (memq 'context-menu org-mouse-features)
865 (org-defkey org-mouse-map [C-drag-mouse-1] 'org-mouse-move-tree)
866 (org-defkey org-mouse-map [C-down-mouse-1] 'org-mouse-move-tree-start))
867 (when (memq 'yank-link org-mouse-features)
868 (org-defkey org-mode-map [S-mouse-2] 'org-mouse-yank-link)
869 (org-defkey org-mode-map [drag-mouse-3] 'org-mouse-yank-link))
870 (when (memq 'move-tree org-mouse-features)
871 (org-defkey org-mouse-map [drag-mouse-3] 'org-mouse-move-tree)
872 (org-defkey org-mouse-map [down-mouse-3] 'org-mouse-move-tree-start))
874 (when (memq 'activate-stars org-mouse-features)
875 (font-lock-add-keywords
877 `((,org-outline-regexp
878 0 `(face org-link mouse-face highlight keymap ,org-mouse-map)
879 'prepend))
882 (when (memq 'activate-bullets org-mouse-features)
883 (font-lock-add-keywords
885 `(("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +"
886 (1 `(face org-link keymap ,org-mouse-map mouse-face highlight)
887 'prepend)))
890 (when (memq 'activate-checkboxes org-mouse-features)
891 (font-lock-add-keywords
893 `(("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
894 (2 `(face bold keymap ,org-mouse-map mouse-face highlight) t)))
897 (defadvice org-open-at-point (around org-mouse-open-at-point activate)
898 (let ((context (org-context)))
899 (cond
900 ((assq :headline-stars context) (org-cycle))
901 ((assq :checkbox context) (org-toggle-checkbox))
902 ((assq :item-bullet context)
903 (let ((org-cycle-include-plain-lists t)) (org-cycle)))
904 ((org-footnote-at-reference-p) nil)
905 (t ad-do-it))))))
907 (defun org-mouse-move-tree-start (_event)
908 (interactive "e")
909 (message "Same line: promote/demote, (***):move before, (text): make a child"))
912 (defun org-mouse-make-marker (position)
913 (with-current-buffer (window-buffer (posn-window position))
914 (copy-marker (posn-point position))))
916 (defun org-mouse-move-tree (event)
917 ;; todo: handle movements between different buffers
918 (interactive "e")
919 (save-excursion
920 (let* ((start (org-mouse-make-marker (event-start event)))
921 (end (org-mouse-make-marker (event-end event)))
922 (sbuf (marker-buffer start))
923 (ebuf (marker-buffer end)))
925 (when (and sbuf ebuf)
926 (set-buffer sbuf)
927 (goto-char start)
928 (org-back-to-heading)
929 (if (and (eq sbuf ebuf)
930 (equal
931 (point)
932 (save-excursion (goto-char end) (org-back-to-heading) (point))))
933 ;; if the same line then promote/demote
934 (if (>= end start) (org-demote-subtree) (org-promote-subtree))
935 ;; if different lines then move
936 (org-cut-subtree)
938 (set-buffer ebuf)
939 (goto-char end)
940 (org-back-to-heading)
941 (when (and (eq sbuf ebuf)
942 (equal
943 (point)
944 (save-excursion (goto-char start)
945 (org-back-to-heading) (point))))
946 (progn (org-end-of-subtree nil t)
947 (unless (eobp) (backward-char)))
948 (end-of-line)
949 (if (eobp) (newline) (forward-char)))
951 (when (looking-at org-outline-regexp)
952 (let ((level (- (match-end 0) (match-beginning 0))))
953 (when (> end (match-end 0))
954 (progn (org-end-of-subtree nil t)
955 (unless (eobp) (backward-char)))
956 (end-of-line)
957 (if (eobp) (newline) (forward-char))
958 (setq level (1+ level)))
959 (org-paste-subtree level)
960 (save-excursion
961 (progn (org-end-of-subtree nil t)
962 (unless (eobp) (backward-char)))
963 (when (bolp) (delete-char -1))))))))))
966 (defun org-mouse-transform-to-outline ()
967 (interactive)
968 (org-back-to-heading)
969 (let ((minlevel 1000)
970 (replace-text (concat (match-string 0) "* ")))
971 (beginning-of-line 2)
972 (save-excursion
973 (while (not (or (eobp) (looking-at org-outline-regexp)))
974 (when (looking-at org-mouse-plain-list-regexp)
975 (setq minlevel (min minlevel (- (match-end 1) (match-beginning 1)))))
976 (forward-line)))
977 (while (not (or (eobp) (looking-at org-outline-regexp)))
978 (when (and (looking-at org-mouse-plain-list-regexp)
979 (eq minlevel (- (match-end 1) (match-beginning 1))))
980 (replace-match replace-text))
981 (forward-line))))
983 (defvar org-mouse-cmd) ;dynamically scoped from `org-with-remote-undo'.
985 (defun org-mouse-do-remotely (command)
986 ;; (org-agenda-check-no-diary)
987 (when (get-text-property (point) 'org-marker)
988 (let* ((anticol (- (point-at-eol) (point)))
989 (marker (get-text-property (point) 'org-marker))
990 (buffer (marker-buffer marker))
991 (pos (marker-position marker))
992 (hdmarker (get-text-property (point) 'org-hd-marker))
993 (buffer-read-only nil)
994 (newhead "--- removed ---")
995 (org-mouse-direct nil)
996 (org-mouse-main-buffer (current-buffer)))
997 (when (eq (with-current-buffer buffer major-mode) 'org-mode)
998 (let ((endmarker (with-current-buffer buffer
999 (org-end-of-subtree nil t)
1000 (unless (eobp) (forward-char 1))
1001 (point-marker))))
1002 (org-with-remote-undo buffer
1003 (with-current-buffer buffer
1004 (widen)
1005 (goto-char pos)
1006 (org-show-hidden-entry)
1007 (save-excursion
1008 (and (outline-next-heading)
1009 (org-flag-heading nil))) ; show the next heading
1010 (org-back-to-heading)
1011 (setq marker (point-marker))
1012 (goto-char (max (point-at-bol) (- (point-at-eol) anticol)))
1013 (funcall command)
1014 (message "_cmd: %S" org-mouse-cmd)
1015 (message "this-command: %S" this-command)
1016 (unless (eq (marker-position marker) (marker-position endmarker))
1017 (setq newhead (org-get-heading))))
1019 (beginning-of-line 1)
1020 (save-excursion
1021 (org-agenda-change-all-lines newhead hdmarker 'fixface))))
1022 t))))
1024 (defun org-mouse-agenda-context-menu (&optional _event)
1025 (or (org-mouse-do-remotely 'org-mouse-context-menu)
1026 (popup-menu
1027 '("Agenda"
1028 ("Agenda Files")
1029 "--"
1030 ["Undo" (progn (message "last command: %S" last-command) (setq this-command 'org-agenda-undo) (org-agenda-undo))
1031 :visible (if (eq last-command 'org-agenda-undo)
1032 org-agenda-pending-undo-list
1033 org-agenda-undo-list)]
1034 ["Rebuild Buffer" org-agenda-redo t]
1035 ["New Diary Entry"
1036 org-agenda-diary-entry (org-agenda-check-type nil 'agenda) t]
1037 "--"
1038 ["Goto Today" org-agenda-goto-today
1039 (org-agenda-check-type nil 'agenda) t]
1040 ["Display Calendar" org-agenda-goto-calendar
1041 (org-agenda-check-type nil 'agenda) t]
1042 ("Calendar Commands"
1043 ["Phases of the Moon" org-agenda-phases-of-moon
1044 (org-agenda-check-type nil 'agenda)]
1045 ["Sunrise/Sunset" org-agenda-sunrise-sunset
1046 (org-agenda-check-type nil 'agenda)]
1047 ["Holidays" org-agenda-holidays
1048 (org-agenda-check-type nil 'agenda)]
1049 ["Convert" org-agenda-convert-date
1050 (org-agenda-check-type nil 'agenda)]
1051 "--"
1052 ["Create iCalendar file" org-icalendar-combine-agenda-files t])
1053 "--"
1054 ["Day View" org-agenda-day-view
1055 :active (org-agenda-check-type nil 'agenda)
1056 :style radio :selected (eq org-agenda-current-span 'day)]
1057 ["Week View" org-agenda-week-view
1058 :active (org-agenda-check-type nil 'agenda)
1059 :style radio :selected (eq org-agenda-current-span 'week)]
1060 "--"
1061 ["Show Logbook entries" org-agenda-log-mode
1062 :style toggle :selected org-agenda-show-log
1063 :active (org-agenda-check-type nil 'agenda)]
1064 ["Include Diary" org-agenda-toggle-diary
1065 :style toggle :selected org-agenda-include-diary
1066 :active (org-agenda-check-type nil 'agenda)]
1067 ["Use Time Grid" org-agenda-toggle-time-grid
1068 :style toggle :selected org-agenda-use-time-grid
1069 :active (org-agenda-check-type nil 'agenda)]
1070 ["Follow Mode" org-agenda-follow-mode
1071 :style toggle :selected org-agenda-follow-mode]
1072 "--"
1073 ["Quit" org-agenda-quit t]
1074 ["Exit and Release Buffers" org-agenda-exit t]
1075 ))))
1077 (defun org-mouse-get-gesture (event)
1078 (let ((startxy (posn-x-y (event-start event)))
1079 (endxy (posn-x-y (event-end event))))
1080 (if (< (car startxy) (car endxy)) :right :left)))
1083 ; (setq org-agenda-mode-hook nil)
1084 (defvar org-agenda-mode-map)
1085 (add-hook 'org-agenda-mode-hook
1086 (lambda ()
1087 (setq org-mouse-context-menu-function 'org-mouse-agenda-context-menu)
1088 (org-defkey org-agenda-mode-map [mouse-3] 'org-mouse-show-context-menu)
1089 (org-defkey org-agenda-mode-map [down-mouse-3] 'org-mouse-move-tree-start)
1090 (org-defkey org-agenda-mode-map [C-mouse-4] 'org-agenda-earlier)
1091 (org-defkey org-agenda-mode-map [C-mouse-5] 'org-agenda-later)
1092 (org-defkey org-agenda-mode-map [drag-mouse-3]
1093 (lambda (event) (interactive "e")
1094 (cl-case (org-mouse-get-gesture event)
1095 (:left (org-agenda-earlier 1))
1096 (:right (org-agenda-later 1)))))))
1098 (provide 'org-mouse)
1100 ;;; org-mouse.el ends here